我有一个自定义的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
这似乎应该有一个简单的解决方案,但我似乎无法找到正确的措辞。
答案 0 :(得分:1)
你应该能够覆盖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)
正确的事情应该发生。