【问题标题】:How is something like 30.seconds.ago implemented?30.seconds.ago 之类的东西是如何实现的?
【发布时间】:2015-11-10 20:18:20
【问题描述】:

我发现了这个问题here

真的很想知道像 30.seconds.ago 这样的东西是如何在 Rails 中实现的。

方法链? Numeric 用法如下: http://api.rubyonrails.org/classes/Numeric.html#method-i-seconds

还有什么?

【问题讨论】:

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


    【解决方案1】:

    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
    

    而且,here 是在 ago 中使用的 sum 方法的实现:

      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]
    

    【讨论】:

      猜你喜欢
      • 2014-03-21
      • 1970-01-01
      • 2020-11-03
      • 2021-07-20
      • 2019-09-09
      • 1970-01-01
      • 2012-05-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多