0

Hi I would like to initialize the attributes of an instance of a ruby object dinamically via some config file, I can do that pretty fast using the following code:

class ApiTester

  def initialize(path= "api_test")
    h = eval(File.open("#{path}/config.hash","r").read)
    h.each do |k,v|
      eval("@#{k}=#{v.class == String ? "\"#{v}\"" :  v }" )
    end
  end

end

How do I give the attribute "@#{k}" the property attr_accessor?

Stefan
  • 109,145
  • 14
  • 143
  • 218
  • 2
    You know what `attr_accessor` does, right? So you can just define those methods in a similar manner with that instance variable. – Sergio Tulentsev Mar 03 '16 at 10:28
  • You should probably define the getters and setters on the *singleton class* of your instance. Otherwise, you will pollute your `ApiTester` class and therefore every instance. Another option is to generate an entire class dynamically, based on the config. – Stefan Mar 03 '16 at 11:27

1 Answers1

5
class ApiTester
  def initialize(path= "api_test")
    h = { a: 1, b: 2 }
    h.each do |k,v|
      instance_variable_set("@#{k}", v)
      self.class.send(:attr_accessor, k)
    end
  end
end

api_tester = ApiTester.new
puts api_tester.a # => 1
puts api_tester.b # => 2

api_tester.a = 3
puts api_tester.a # => 3

By the way, you should probably create a .yaml file and use YAML::load_file, it is best practice to avoid eval if you can.

Leventix
  • 3,789
  • 1
  • 32
  • 41