Here là việc thực hiện các seconds
:
def seconds
ActiveSupport::Duration.new(self, [[:seconds, self]])
end
Và, here là việc thực hiện các ago
:
# 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
Và, here là việc thực hiện các phương pháp sum
đó là sử dụng bên trong 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
Để hiểu nó đầy đủ, bạn nên thực hiện theo các cuộc gọi phương thức và tìm cách triển khai của chúng trong mã nguồn Rails như tôi đã chỉ cho bạn ngay bây giờ.
Một cách dễ dàng để tìm một định nghĩa phương pháp bên trong cơ sở Rails đang sử dụng source_location
trong Rails giao diện điều khiển của bạn:
> 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]
Nguồn
2015-11-10 20:23:38