【问题标题】:Monkey patch for created_atcreated_at 的猴子补丁
【发布时间】:2012-05-08 22:51:08
【问题描述】:

我正在尝试编写一个猴子补丁来为 created_at 添加一个方法。

我创建了一个date_time_extras.rb文件,放到lib目录下,内容:

class DateTime
  def beginning_of_hour
    change(:min => 0)
  end
end

从我做的控制台:

record.created_at.beginning_of_hour

但这会产生方法丢失错误。看起来 created_at 不是日期时间?因为DateTime.new.beginning_of_hour 有效,而record.created_at.class 产生ActiveSupport::TimeWithZone

那么如何为 created_at 类型的日期编写猴子补丁呢?

我使用的是 Rails 版本 3.0.10。

更新

也试过了

module ActiveSupport
  class TimeWithZone
    def beginning_of_hour
      change(:min => 0)
    end
  end
end

无济于事

【问题讨论】:

  • Welp.. 在此期间,看起来我可以使用 record.created_at.change(:min => 0)

标签: ruby-on-rails-3 monkeypatching


【解决方案1】:

您是否尝试在class Time 中声明它?

class DateTime
  def beginning_of_hour
    change(:min => 0)
  end
end

TimeWithZone 看起来像是将其时间对象委托给 Time 而不是 DateTime

此外,TimeWithZone 不仅包含 @time 对象,因此您必须执行类似的操作

module ActiveSupport
  class TimeWithZone
    def beginning_of_hour
      self.time.change(:min => 0)
    end
  end
end

但我不能 100% 确定该代码。

【讨论】:

    猜你喜欢
    • 2016-09-01
    • 2012-09-16
    • 2012-12-18
    • 2020-01-09
    • 1970-01-01
    • 1970-01-01
    • 2010-09-29
    • 2021-04-04
    • 2011-04-15
    相关资源
    最近更新 更多