微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ruby-on-rails – 30.seconds.ago如何实现?

我发现了这个问题 here.

并且真的很想知道在Rails中实现类似30.seconds.ago的技术解释.

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

还有什么?

解决方法

Here是秒的执行:
def seconds
    ActiveSupport::Duration.new(self,[[:seconds,self]])
  end

并且,here是以前的实施:

# 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方法的实现:

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]

原文地址:https://www.jb51.cc/ruby/264756.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐