7

我在这里找到了这个问题。

30.seconds.ago真的很想知道如何在 Rails 中实现类似的东西的技术解释。

方法链?Numeric按照以下方式使用:http: //api.rubyonrails.org/classes/Numeric.html#method-i-seconds

还有什么?

4

1 回答 1

12

是的实现seconds

  def seconds
    ActiveSupport::Duration.new(self, [[:seconds, self]])
  end

而且,这里是实现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

而且,是在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 代码库中查找方法定义的一种简单方法是source_location在 Rails 控制台中使用:

> 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]
于 2015-11-10T20:23:38.767 回答