我有一个模型,其中包含一些相关的日期字段。
def started_at_date=(value)
@started_at_date = value
end
def completed_at_date=(value)
@completed_at_date = value
end
...
吸气剂通过method_missing
处理,效果很好。
def method_missing(method, *args, &block)
if method =~ /^local_(.+)$/
local_time_for_event($1)
elsif method =~ /^((.+)_at)_date$/
self.send :date, $1
elsif method =~ /^((.+)_at)_time$/
self.send :time, $1
else
super
end
end
def date(type)
return self.instance_variable_get("@#{type.to_s}_date") if self.instance_variable_get("@#{type.to_s}_date")
if self.send type.to_sym
self.send(type.to_sym).in_time_zone(eventable.time_zone).to_date.to_s
end
end
...
我想动态添加二传手,但我不确定如何以避免ActiveRecord::UnknownAttributeError
的方式这样做。
我认为这会起作用:
def method_missing(method, *args, &block)
super unless method =~ /_date$/
class_eval { attr_accessor method }
super
end
你能只使用虚拟属性吗?
Class Whatever < ApplicationModel
attr_accessor :started_at_date
attr_accessor :completed_at_date
#if you want to include these attributes in mass-assignment
attr_accessible :started_at_date
attr_accessible :completed_at_date
end
当您稍后需要访问属性而不是调用@started_at_date时,您将调用self.started_at_date等。
如果我理解正确,请尝试:
# in SomeModel
def self.new_setter(setter_name, &block)
define_method("#{setter_name}=", &block)
attr_accessible setter_name
end
用法:
SomeModel.new_setter(:blah) {|val| self.id = val }
SomeModel.new(blah: 5) # => SomeModel's instance with id=5
# or
@sm = SomeModel.new
@sm.blah = 5