Our Daily Method #19: Time#method_missing
Geplaatst door Michiel de Mare wo, 05 maa 2008 13:43:00 GMT
Our stock of cool tricks is depleted, but inspiration still strikes once in a while.
Are you using strftime
a lot? Do you like writing strfime
? Have you ever spelled it as strtime
? strf_time
? Thought it was frmtstr
?
And if you spell it right, you still have to type those stupid %-signs. All in all, room for improvement.
class Time
def method_missing(name,*args)
if name.to_s =~ /f_/
c = args[0] || ' '
x = name.to_s[2..-1].split(//).
map {|f| f =~ /[a-z]/i ? "%"+f : c}.
join
strftime(x)
else
super
end
end
end
So, how does it work?
It handles every method starting with f_
. What follows are the characters used within strftime
: Y for 4-digit year, d for day of month, etc. Underscores are converted to spaces, or to the first argument, if you provide one.
Examples:
# standard lib
Time.now.strftime("%Y%j") #=> "2008065"
Time.now.strftime("s") #=> "1204725800"
Time.now.strftime("%d %m %Y") #=> "05 03 2008"
Time.now.strftime("%d-%m-%Y") #=> "05-03-2008"
Time.now.strftime("%d %b %Y") #=> "05 Mar 2008"
# new and improved
Time.now.f_Yj #=> "2008065"
Time.now.f_s #=> "1204725800"
Time.now.f_d_m_Y #=> "05 03 2008"
Time.now.f_d_m_Y('-') #=> "05-03-2008"
Time.now.f_d_b_Y #=> "05 Mar 2008"
Cool? Stupid? Why don’t you play with it ?
f_ evaluates it as “%s”, not as “s”
Time.now.strftime(“%s”), or number of seconds since the Epoch, is not working on the windows platform. Time.now.strftime.to_i gives the same result, and is also working on windows.
Time.now – Time.now.to_i # Epoch
Time.now + 30 * 86400 * 365 # Y2038 bug