So I’m thinking of using method missing to construct several datetime methods that I need for the large number of datetimes that I have to manage.
I am basing this method on Ryan Bates virtual attributes and believe I have this metaprogramming challenge down (my 1st one!) except for one little snafu that I haven’t yet solved…
For this part of my method I am getting an error concerning the = which is supposed to be unexpected…
define_method(save_method) do
self.send(attribute) = Chronic.parse(args[0], context: :past) if instance_variable_get("@#{method_name}").present?
end
The method is supposed to be expecting a ) instead…but I haven’t been able to figure it out.
def method_missing(method_name, *args)
if method_name.to_s.match(/^chronic_(\w+)/)
save_method = "save_#{method_name}"
validate_method = "check_#{method_name}"
attribute = method_name.to_s.gsub(/^chronic_/, '').to_sym
self.class.class_eval do
attr_accessible method_name.to_sym
attr_writer method_name.to_sym
validate validate_method.to_sym
before_save save_method.to_sym
define_method(save_method) do
self.send(attribute) = Chronic.parse(args[0], context: :past) if instance_variable_get("@#{method_name}").present?
end
define_method(validate_method) do
if instance_variable_get("@#{method_name}").present? && Chronic.parse(args[0], context: :past).nil?
errors.add :released_at_text, "cannot be parsed"
end
end
define_method(method_name) do
instance_variable_get("@#{method_name}") || attribute
end
end
puts attribute
send(method_name)
else
super
end
end
“
=” is a part of method of setter method name so you have tosend("#{attribute}=", value)