隨筆-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
          主站蜘蛛池模板: 百色市| 东阳市| 临安市| 招远市| 怀宁县| 宜兴市| 六盘水市| 曲阜市| 吉木萨尔县| 平果县| 涞源县| 肇源县| 望城县| 大渡口区| 门头沟区| 曲沃县| 大洼县| 漯河市| 溧阳市| 沂南县| 合水县| 瓮安县| 南江县| 莲花县| 嘉定区| 凤翔县| 渝中区| 乌审旗| 南部县| 诸暨市| 香港| 凤翔县| 齐齐哈尔市| 大石桥市| 唐海县| 上饶县| 芒康县| 平山县| 湖州市| 虹口区| 泰兴市|