Dynamic properties in ruby class

248 Views Asked by At

How can I create a dynamic property in ruby? This functionality exists in python.

class Example(object):
    value = "This is property!"

class Test(object):
    @property
    def check(self):
        return Example

test = Test()
print(test.check.value)  # This is property!

How can I do the same in ruby?

4

There are 4 best solutions below

0
On BEST ANSWER
class Example
  def value
    "This is property!"
  end
end

class Test
  def check
    Example.new
  end
end

test = Test.new
puts test.check.value  # This is property!
1
On
class Test
  def check
   "This is property!"
  end
end

test = Test.new
puts(test.check) # This is property!
0
On

Not sure what you want from your example. Properties (from what I've seen) are usually used to create setters and getters. You can have that in Ruby with attr_accessor:

class Test
  attr_accessor :check
end

You can call attr_accessor anytime you want an attribute:

class Test
  %w{this are possible attribute names}.each do |att|
    attr_accessor att
  end
end

Or

Class Test
end

test = Test.new
Test.send(:attr_accessor, :whatever)
test.whatever = "something"
test.whatever # => "something"

If you only want a getter you have attr_reader, and there's attr_writer for a writer. They all, for an attribute called attribute_name, use an instance variable called @attribute_name. They all may be built with instance_variable_set and instance_variable_get, which allow dynamically setting and getting instance variables.

0
On

You can use ruby's method_missing to achieve something similar:

class TestCheck
  def method_missing(methodId)
    if(methodId.id2name == "check")
      puts "check called"
    else
      puts "method not found"
    end
  end

end

t = TestCheck.new
t.check      #=> "check called"
t.something_else   #=> "method not found"

Reference: Ruby docs