Bob Bob - 6 months ago 14
Ruby Question

Rails 3 add virtual attribute dynamically

My setup: Rails 3.0.9, Ruby 1.9.2

I have my reasons for doing this but what I need is a way to add a virtual attribute to an activerecord resultset dynamically. That means I am not using

attr_accessor
in the model and instead wish to dynamically add virtual attributes to a resultset.

For example,

users = User.all
#a user has following attributes: name, email, password


What I like to do is say add (without using
attr_accessor
) a virtual attribute
status
to
users
, is that possible?

Answer

You should do this:

users.each do |user|
  user.instance_eval do
    def status
      instance_variable_get("@status")
    end        
    def status=(val) 
      instance_variable_set("@status",val)
    end
  end
end