-1

It's as the question title says, I have an included hook in a module:

def self.included(base)
    puts 'included'
    base.extend API
end

My API requires certain variables on the object to exists but none of them are being created.

I've tried:

  1. base.variable_name = []
  2. %x|#{base}.variable_name = []|
  3. base.instance_variable_set(:@variable_name,[])
  4. base.instance_exec{@variable_name = []}
  5. 1-2 inside of base.instance_exec but using self instead of base

Yet none of them work, the console just complains that variable_name= doesn't exist.

What.the.hell?

How do I get the variable to exist on the base object inside of the included hook?

Community
  • 1
  • 1
Thermatix
  • 2,757
  • 21
  • 51
  • 1
    You are mixing class and instance up. `base` here is a `Class` object. Setting instance variable on it makes no sense. You might try [`attr_accessor`](http://ruby-doc.org/core-2.1.0/Module.html#method-i-attr_accessor): `base.send :attr_accessor, :variable_name`. The latter will make accessors for this var for each instance. Other way is to patch `initialize`, but it seems to be an overkill here. Setting value here is impossible, since at this moment there is no _instance_. Other way would be to define getter and setter for those vars explicitly, using `define_method`. – Aleksei Matiushkin Aug 19 '15 at 12:10
  • I've actually tried `base.attr_accessor :some_variable` but I'll try it using the send method instead, if not then I guess I'l just do it using a setter and getter. – Thermatix Aug 19 '15 at 12:53

1 Answers1

0

In the end, I had to use @variable_name ||= [] inside of the function definitions themselves to get it to work, I don't like it but it works.

If you want to know why I don't like it's because defining object attributes in once places means I can easily find where they're defined and change the initial value, whereas here I have to track it down to change it (not hard but it's the principle).

Personal preference I guess.

Thermatix
  • 2,757
  • 21
  • 51