0

I would like to define the variable @@importers when my module loads.

module Importers
  @@importers_dir = File.dirname(__FILE__) + '/services/'
  @@importers = self.load_and_instantiate()
  def self.load_and_instantiate()
     #mycode here
  end
end

But it does not work :

undefined method 'load_and_instantiate' for Importers:Module (NoMethodError)

How should I handle this ?

Thanks !

gordie
  • 1,637
  • 3
  • 21
  • 41
  • I've not seen a class variable defined in a module (and rarely see a class variable defined anywhere, for good reason). I assume you realize that if `Importers` is included in a class the class will acquire those class variables with the computed values (e.g., `module M; @@v = 1; end; class C; include M; end; C.class_variable_get(:@@v) #=> 1`). If `Importers::load_and_instantiate` is created only for assigning a value to `@@importers` then just write `@@importers = #mycode here`. Lastly, empty parentheses are not generally shown when methods are invoked without arguments. – Cary Swoveland Jan 28 '20 at 17:26

1 Answers1

2

At the moment you call load_and_instantiate it is indeed not defined because you define it later in the code.

Just change the order and call the method after you defined the method:

def self.load_and_instantiate
  # mycode here
end

@@importers = self.load_and_instantiate

Please note that using class variables is uncommon in Ruby.

spickermann
  • 100,941
  • 9
  • 101
  • 131
  • 1
    @gordie Most of the time a [class instance variable](https://stackoverflow.com/questions/15773552/ruby-class-instance-variable-vs-class-variable). – 3limin4t0r Jan 28 '20 at 13:54
  • ...or `@@importers = load_and_instantiate`, as `load_and_instantiate`'s receiver, if not specified, equals `self`. – Cary Swoveland Jan 28 '20 at 16:32