Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 877
Bob Avatar asked Sep 01 '11 22:09

Bob


1 Answers

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
like image 106
apneadiving Avatar answered Oct 05 '22 00:10

apneadiving