随笔-167  评论-65  文章-0  trackbacks-0
ruby 1.8.7 + rails 2.1.0

在用到rails <%= time_ago_in_words(activity.created_at).capitalize %> 之前 方法时 , 输出的结果默认是英文的。。如下

需要重写原来的方法,用的是rails2.1.0 如果是rails 2.2.2之后的,貌似可以使用I18N的。。所以只好重写method了
刚开始是放在lib下, 然后在enviroment.rb中require的,但是后来没有成功,只好放在initializers中了

新建 date_helper.rb:(可以随便命名)

module ActionView
  module Helpers
    module DateHelper
      def distance_of_time_in_words(from_time, to_time = 0, include_seconds = false)
        from_time = from_time.to_time if from_time.respond_to?(:to_time)
        to_time = to_time.to_time if to_time.respond_to?(:to_time)
        distance_in_minutes = (((to_time - from_time).abs)/60).round
        distance_in_seconds = ((to_time - from_time).abs).round

        case distance_in_minutes
        when 0..1
          return (distance_in_minutes == 0) ? '少于1分钟' : '1 分钟' unless include_seconds
          case distance_in_seconds
          when 0..4   then '少于 5 秒'
          when 5..9   then '少于 10 秒'
          when 10..19 then '少于 20 秒'
          when 20..39 then '半分钟'
          when 40..59 then '少于 1 分钟'
          else             '1 分钟'
          end

        when 2..44           then "#{distance_in_minutes} 分钟"
        when 45..89          then '大概 1 小时'
        when 90..1439        then "大概 #{(distance_in_minutes.to_f / 60.0).round} 小时"
        when 1440..2879      then '1 天'
        when 2880..43199     then "#{(distance_in_minutes / 1440).round} 天"
        when 43200..86399    then '大概 1 个月'
        when 86400..525599   then "#{(distance_in_minutes / 43200).round} 个月"
        when 525600..1051199 then '大概 1 年'
        else                      "超过 #{(distance_in_minutes / 525600).round} 年"
        end
      end
    end
  end
end   


原来的方法,可以到
/usr/lib/ruby/gems/1.8/gems/actionpack-2.1.0/lib/action_view/helpers/date_helper.rb 中找到

之后重启服务,okay了。。。。。。

ref:
http://www.nabble.com/Rails-2.1-and-ddatetime_select-td17726324.html
http://hervalicio.us/blog/2007/05/10/translating-time_ago_in_words/#comment-16360
http://fsjoy.blog.51cto.com/318484/119541



write by feng
posted on 2009-08-18 17:48 fl1429 阅读(580) 评论(0)  编辑  收藏 所属分类: Rails

只有注册用户登录后才能发表评论。


网站导航:
 
已访问数:
free counters