Answer the question
In order to leave comments, you need to log in
How to do metaprogramming or how easy it is to program autocompletion of methods (attr_accessor)?
I think I'm beginning to understand the "meaning of life"
Here's an example:
class Derp
attr_reader :success
def initialize
@success = Success.new
@sum = 3
@a = 5
end
def boom
@success.sum = @sum
@success.a = @a
end
end
class Success
attr_accessor :sum, :a
end
obj = Derp.new()
obj.boom
puts obj.success.sum
Answer the question
In order to leave comments, you need to log in
Hello, I can immediately name 2 ways how to do this.
The first way is to use the __send__ method :
class Success
def new_accessor(attribute)
self.class.__send__(:attr_accessor, attribute)
end
end
class Success
def new_accessor(attribute)
self.class.class_eval { attr_accessor attribute }
end
end
The question is, is it necessary? In a serious project, it can easily add unnecessary crap during debugging and support.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question