undefined method `length' for Enumerable when calling truncate method

With rails 2.0.2 and ruby 1.8.7 you can find this error using rails truncate helper

To solve this problem, paste this code in your enviroment.rb (eof).

module ActionView
  module Helpers
    module TextHelper
      def truncate(text, length = 30, truncate_string = "...")
        if text.nil? then return end
        l = length - truncate_string.chars.to_a.size
        (text.chars.to_a.size > length ? text.chars.to_a[0...l].join + truncate_string : text).to_s
      end
    end
  end
end

Have a nice day!

Incompatible with Ruby 1.8.7

If using Rails < 2.2 with Ruby 1.8.7, calling truncate will result in the following error:

  undefined

 method

 `length

'

 for #<Enumerable::Enumerator:0xb74f952c> 



The workaround (other than upgrading to Rails 2.2 or higher), is to overwrite the truncate method, by inserting the following at the end of environment.rb (or where it will be called on startup):

你可能感兴趣的:(Ruby,Rails)