隨筆-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 閱讀(602) 評論(0)  編輯  收藏 所屬分類: Rails
          已訪問數:
          free counters
          主站蜘蛛池模板: 嘉定区| 榕江县| 泌阳县| 喜德县| 罗山县| 井研县| 松原市| 乐安县| 松阳县| 阳西县| 河间市| 抚顺市| 佳木斯市| 台东市| 永川市| 苏尼特左旗| 九龙城区| 酉阳| 桃园县| 裕民县| 宣威市| 宁南县| 夏河县| 宜君县| 平昌县| 原阳县| 松阳县| 彰化县| 大新县| 大港区| 蕉岭县| 平凉市| 南澳县| 库车县| 仪征市| 长乐市| 定南县| 永登县| 精河县| 陕西省| 九龙县|