A
A
Alexander Grishin2016-03-10 19:37:41
Ruby on Rails
Alexander Grishin, 2016-03-10 19:37:41

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

How, for example, to add the accessor - abc method to Success on the fly ? And the main question is whether it is necessary (if you can give an example for the especially gifted))? And another question - how does it affect performance in this case (only without a holivar, otherwise it will start)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton Davydov, 2016-03-17
@beerdy

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

The second way is to use class_eval :
class Success
  def new_accessor(attribute)
    self.class.class_eval { attr_accessor attribute }
  end
end

But a reasonable question arises: is it really necessary? As said above, debugging all this magic is very difficult. In addition, thanks to this, you can greatly complicate the understanding of the code.

A
Andrey Sapozhnikov, 2016-03-17
@Skarm61

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 question

Ask a Question

731 491 924 answers to any question