我正在尝试编写一个猴子补丁来为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
无济于事
答案 0 :(得分:0)
您是否尝试在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%肯定。