query: tag:hack

Redmineで2203年の予定を立てようとしたところ、エラーが出たので原因を調べていました。
どうやら、Railsのdistance_of_time_in_wordsでエラーが出ているようです。

ruby>>
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
<<--

8行目あたりの減算でエラーが出ているようです。
実際、以下のような減算をしようとするとエラーが出ます。

ruby>>
Time.now - Date.parse("Mon, 01 Aug 2203").to_time
#=> RangeError: time - 7371010800.000000 out of Time range
<<--

ということで、あまりにも長い時間である場合には、
以下のような例外処理で対処するようにしました。

ruby>>
module ActionView
module Helpers
module DateHelper
def distance_of_time_in_words_with_limit(
from_time, to_time = 0, include_seconds = false
)
distance_of_time_in_words_without_limit(
from_time, to_time, include_seconds)
rescue
'a long time'
end
alias_method_chain :distance_of_time_in_words, :limit
end
end
end
<<--

これで23世紀の予定も思いのままです。

posted by genki genki on Fri 8 Aug 2008 at 06:44 with 0 comments

Railsのroutes.rbでNamed Routeを利用するときに、
メソッド名の競合などで通常は使えない名前をどうしても
利用したい場合、以下のように記述することで利用できます。

config/routes.rb

rails>>
map.send :method_missing, :touch, 'foo/:id/touch', :action => 'touch'
<<--

メソッドがすでに定義されているため、method_missing
が呼ばれなくなっている状態を無理やり回避しています。

posted by genki genki on Mon 26 Nov 2007 at 15:03 with 0 comments