Defining ghost methods for attributes in Ruby on Rails

604 views Asked by At

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.

1

There are 1 answers

0
SergeyKutsko On BEST ANSWER

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