`

ruby-1.8.7中truncate方法重写

阅读更多

在ruby-1.8.7中的运用方法truncate会存在问题,有些属性无法识别,所以在ruby-1.8.7中如果要使用方法truncate 实现字符串截取并替换的功能的话,就需要对这个方法进行重写。我们可以把这个方法写在位于/config/environment.rb中,具体的方法可 以这样写:

module ActionView
  module Helpers
    module TextHelper
      def truncate(text, length = 20, 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

添加完成后,重新启动mongrel,在调用这个方法的地方就不会报错了,实现了我们想要实现的功能。这个bug在版本1.8.6中以及后面跟进的版本1.9中是不存在的。

2
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics