rubyvariablesmoduleopalrb

Can't create variable on base object in 'self.included' hook in Opal


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?


Solution

  • 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.