ruby-on-rails - 是否有 ruby​​/rails gem 可以轻松确定日期范围

标签 ruby-on-rails ruby date gem

有人知道可以轻松确定日期范围的 gem 吗?我很想做 Model.this_year(:created_at).where()... 等。以为我听说过一次。

我在考虑 dues_paid_this_year 或 updated_at_two_hours_ago 的思路。一个 gem 可以像 search_logic 那样通过创建动态范围来做到这一点会让我的世界变得可爱

最佳答案

我不知道有什么 gem ——尽管创造一个 gem 会很酷。话虽这么说,这可能会让你通过:

class Thing < ActiveRecord::Base
  # Some date-related scopes
  scope :today, where("created_at > ?", Time.now.beginning_of_day)
  scope :yesterday, where("created_at < ? and created_at > ?", 1.day.ago.end_of_day, 1.day.ago.beginning_of_day)
  scope :this_month, where("created_at > ?", Time.now.beginning_of_month)
  scope :last_month, where("created_at < ? and created_at > ?", 1.month.ago.end_of_month, 1.month.ago.beginning_of_month)
  scope :this_year, where("created_at > ?", Time.now.beginning_of_year)
  ### 
  # All your model stuff goes here
  ###

  # Let's get real tricky with method_missing 
  # and allow Thing.last_X_days for work for any value of X
  private

  def self.method_missing(method, *args, &block) 
    if method.to_s =~  /^last_(\d+)_days$/i
      days = method.to_s.match(/^last_(\d+)_days$/i)
      return self.where("created_at > ?", days[1].to_i.days.ago.beginning_of_day)
    else
      super
    end
  end   

end

这将为您提供一些基本范围,例如 Thing.this_month ... 以及一个动态查找器,让您可以执行类似 Thing.last_90_days 的操作并处理任何数字(警告:我有点 method_missing n00b,代码对我有用,但也许有人可以仔细检查它)。

仅供引用,我在这里假设使用 Rails 3。

关于ruby-on-rails - 是否有 ruby​​/rails gem 可以轻松确定日期范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7180892/

相关文章:

html - 为什么我的网站没有使用我指定的字体?无法访问字体?

ruby-on-rails - 将MongoMapper对象中的嵌套对象包含在JSON响应中

ruby-on-rails - 如何在 Heroku 上的 Rails 应用程序中计算箱线图(四分位数、中位数)的数据? (Heroku 使用 Postgresql)

ruby - 如何在 ruby​​ 中删除所有非数字符号(逗号和破折号除外)

java - 无法解析 Twitter 中的日期

php - 今天在特定时间的 Unix 时间戳

ruby-on-rails - 是否可以在 Rails 中更改 URL 中的 Controller 名称

ruby-on-rails - 如果有的话,rspec 相对于 test::unit 的主要优势是什么?

Ruby:如何将变量从服务器传递到索引?

shell - 如何使用今天的日期重命名现有文件