Paul
Paul

Reputation: 26690

Rails initializer - what is wrong

This is my first initializer and I do not understand what is wrong.

config\initializers\other_server.rb:

OtherServer.setup do |config|
  config.first_server_login = 'qwertyuiop'
  config.first_server_password = '12345'
end

lib\other_server_base.rb:

module OtherServer
  mattr_accessor :first_server_login
  @@first_server_login = nil

  mattr_accessor :first_server_password
  @@first_server_password = nil

  def self.setup
    yield self
  end

  class Base
    def self.session_id
      # ................
      # How to access first_server_login and first_server_password here?
      res = authenticate({
          login: first_server_login,
          pass: first_server_password })
      # ................
    end
  end
end

lib\other_server.rb:

module OtherServer
  class OtherServer < Base
    # ................
  end
end

How to access first_server_login and first_server_password in OtherServer::Base class?

If I call OtherServer.first_server_login it complains about absence of OtherServer::OtherServer.first_server_login member.

Upvotes: 0

Views: 118

Answers (2)

Paul
Paul

Reputation: 26690

I've found the right answer:

A module and a class inside of it CAN have same names. In my case the module members should be referenced as:

::OtherServer.first_server_login

That's all.

Upvotes: 1

Kostas Rousis
Kostas Rousis

Reputation: 6098

Firstly, you can not use the same identifier for both a module and a class.

module Test;end # => nil
class Test;end  # => TypeError: Test is not a class

Beyond that, regarding your first snippet, the variable would not be able to be resolved as it would try to resolve it within the Base class which doesn't extend OtherServer (is just defined within its namespace). You could still access it like that:

class Base
  def self.session_id      
    OtherServer.first_server_login # this works
  end
end

Upvotes: 0

Related Questions