Reputation: 6616
How does method chaining work in ruby? As a C# developer, when I see 1.hour.from_now.localtime
, I'm not sure what's going on. How does this code work?
<%= 1.hour.from_now.localtime %>
Upvotes: 2
Views: 250
Reputation: 2762
1
is an object that responds to hour
pry(main)> 1.class
=> Fixnum
.hour
is a method on Fixnum that signifies it as an hour (by changing it to 3600)
pry(main)> 1.hour.class
=> Fixnum
pry(main)> 1.hour.to_i
=> 3600
.from_now
changes the type of 3600
to a DateTime, 3600 seconds in to the future.
pry(main)> 1.hour.from_now
=> Mon, 22 Sep 2014 19:57:05 UTC +00:00
pry(main)> 1.hour.from_now.class
=> ActiveSupport::TimeWithZone
.localtime
changes the TimeZone to the system local time:
pry(main)> 1.hour.from_now.localtime
=> 2014-09-22 12:57:41 -0700
Upvotes: 13
Reputation: 2432
Everything in Ruby is an object, so in this case:
1
object receives the message hour
3600 seconds
receives the message from_now
ActiveSupport::TimeWithZone
objectfrom_now
) by an offset (our initial Fixnum of seconds)localtime
If you want to explore each step, you can use the rails console and evaluate each step to see the return value (and call class
on each step to see how it changes the type)
Upvotes: 5