我有一个自定义的Interval类,我想在一些不同的ActiveRecord模型中使用。目前,我将间隔存储为具有特定语法的字符串(带有用于强制格式化的自定义验证器),并且在需要访问Interval方法时随时创建一个新对象。
我需要添加什么到ActiveRecord模型/ Interval类中,才能将间隔用作对象而不是字符串,同时仍使用特定语法将间隔存储在数据库中?
希望这是有道理的,但如果没有希望的话,下面的示例将使您解决问题。
ActiveRecord类当前看起来像:
class MyClass < ActiveRecord::Base
validates :interval, allow_blank: true, interval: true # custom validator
...
为了做任何有用的事情,我创建了一个新的间隔:
def some_helper
...
interval_object = Interval.new(@my_class.interval) # @my_class.interval is just a string with specific syntax
if interval_object.useful? # 'useful' method
...
但我想这样做:
def some_helper
...
if @my_class.interval.useful? # 'useful' method
...
初始化期望的时间间隔语法:
3:day # represents every 3 days
1:week # represents every week
这似乎应该有一个简单的解决方案,但我似乎找不到正确的措词。
您应该能够重写accessor和mutator方法来完成需要做的事情:
def interval
Interval.new(super)
end
def interval=(i)
# Or whatever needs to be done to convert `i` back to a string,
# keep in mind that `i` might be a string already.
super(i.to_s)
end
然后,您可以说出以下内容:
@my_class.interval.useful?
@my_class.interval = some_interval_object
@my_class.interval = some_string_that_looks_right
@my_class.update_attributes(:interval => some_interval_object)
@my_class.update_attributes(:interval => some_string_that_looks_right)
正确的事情应该发生。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句