Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically Create Class Attributes with attr_accessor

Tags:

ruby

In Ruby, is there a way to dynamically add a instance variable to a class? For Example:

class MyClass

  def initialize
    create_attribute("name")
  end 

  def create_attribute(name)
    attr_accessor name.to_sym
  end

end

o =  MyClass.new
o.name = "Bob"
o.name
like image 245
dhulihan Avatar asked Nov 02 '10 22:11

dhulihan


2 Answers

One way (there are others) is to use instance_variable_set and instance_variable_get as so:

class Test
    def create_method( name, &block )
        self.class.send( :define_method, name, &block )
    end

    def create_attr( name )
        create_method( "#{name}=".to_sym ) { |val| 
            instance_variable_set( "@" + name, val)
        }

        create_method( name.to_sym ) { 
            instance_variable_get( "@" + name ) 
        }
    end
end

t = Test.new
t.create_attr( "bob" )
t.bob = "hello"
puts t.bob
like image 91
Reese Moore Avatar answered Oct 18 '22 14:10

Reese Moore


maybe ,

instance_variable_set(name,value)

is what your want!

eg:

class Mclass
  def show_variables
    puts self.class.instance_variables
  end
end

Mclass.instance_variable_set(:@test,1)
o=Mclass.new
o.show_variables

you know, class is object too.

like image 22
psjscs Avatar answered Oct 18 '22 16:10

psjscs