30.seconds.ago是如何实现的?

时间:2015-11-10 20:18:20

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-4 ruby-on-rails-5

我发现了这个问题here

非常想知道在Rails中如何实现30.seconds.ago之类的技术解释。

方法链接? Numeric使用情况: http://api.rubyonrails.org/classes/Numeric.html#method-i-seconds

还有什么?

1 个答案:

答案 0 :(得分:11)

Hereseconds

的实现
  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

并且heresum中使用的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]