Question

I want to be able to dynamically add to when there is no corresponding attribute in the database

attr_accessor

This overwrote the attributes I currently had:

def method_missing(method, arg)
  self.class.attr_accessor.send(method) || super
end

I also tried loading the variables into the singleton class, but that gave me a 0 for 1 argument error.

Was it helpful?

Solution

That is you want?

def method_missing(method, *args)
  if method.to_s['=']
    self.define_singleton_method(method) do |*args|
      self.instance_variable_set("@#{method[0..-2]}", args.first)
    end
  else
    self.define_singleton_method(method) do
      self.instance_variable_get("@#{method}")
    end
  end
  self.send(method, *args) rescue super
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top