Kocur4d
Kocur4d

Reputation: 6931

rails auto-loading and initializers

I have a simple module with a basic configuration pattern and API connect method. I am configuring this module in initializer.

services/tasks_manager.rb:

module TasksManager
  class << self
    attr_reader :client
  end

  def self.configuration
    @configuration ||= Configuration.new
  end

  def self.configure
    yield configuration
  end

  def self.connect
    @client ||= SecretAPI::Client.new do |config|
      config.url = configuration.url
      config.token = configuration.token
      config.username = configuration.username
      config.password = configuration.password
    end
    self
  end

#.
#.
# other stuff
#.
#.

  class Configuration
    attr_accessor :url
    attr_accessor :username
    attr_accessor :token
    attr_accessor :password
  end
end

config/initializers/tasks_manger.rb

TasksManager.configure do |config|                                                                                                 
  config.url = "a..."                                                                                         
  config.username = "b..."                                                                               
  config.password = "c..."                                                                               
  config.token = "d..."                                                                                      
end  

When I start rails app all is working fine I can use TasksManager by different objects and it is using configuration that has been set up in initializer. But...

When I make a small change to the services/tasks_manager.rb file, like commenting something out or adding new method to it. I am required to restart the rails app. TasksManager.configuration is empty at this stage. It looks like making a changes to the file forces creation of the new module and initializer is not loaded.

It might be a normal behaviour but it took me a while to figure it out and I was thinking that maybe someone will be able to explain it to me.

I am using rails 4.2 with spring(is it why?).

Upvotes: 0

Views: 309

Answers (1)

phoet
phoet

Reputation: 18845

you can put your initialization-code into a ActionDispatch::Callbacks.to_prepare {} block. that will evaluate it whenever rails reloads classes.

Upvotes: 2

Related Questions