Hereはseconds
の実装です:
def seconds
ActiveSupport::Duration.new(self, [[:seconds, self]])
end
そして、hereago
の実装です:
# Calculates a new Time or Date that is as far in the past
# as this Duration represents.
def ago(time = ::Time.current)
sum(-1, time)
end
そして、hereは内部で使われていますsum
メソッドの実装でありますago
:
def sum(sign, time = ::Time.current) #:nodoc:
parts.inject(time) do |t,(type,number)|
if t.acts_like?(:time) || t.acts_like?(:date)
if type == :seconds
t.since(sign * number)
else
t.advance(type => sign * number)
end
else
raise ::ArgumentError, "expected a time or date, got #{time.inspect}"
end
end
end
これを完全に理解するには、メソッド呼び出しに従って、直前に示したようにRailsのソースコードで実装を探してください。
Railsのコードベース内のメソッド定義を見つけるための簡単な方法は、あなたのRailsコンソールで
source_location
を使用することです
:
> 30.method(:seconds).source_location
# => ["/Users/rislam/.rvm/gems/ruby-2.2.2/gems/activesupport-4.2.3/lib/active_support/core_ext/numeric/time.rb", 19]
> 30.seconds.method(:ago).source_location
# => ["/Users/rislam/.rvm/gems/ruby-2.2.2/gems/activesupport-4.2.3/lib/active_support/duration.rb", 108]