Search code examples
ruby-on-railsruby

Own configure block method not found in initializer


I'm trying to make own configuration for my lib code according to this: https://robots.thoughtbot.com/mygem-configure-block

lib/imodule/imodule.rb:

module Imodule
  class << self
    attr_accessor :configuration
  end

  def self.configure
    self.configuration ||= Configuration.new
    yield(configuration)
  end

  class Configuration
    attr_accessor :api_key
    attr_reader :api_url

    def initialize
      @api_url = 'https://api.test.com'
    end
  end
end

initializers/imodule.rb:

Imodule.configure do |c|
  c.api_key = '4db6-93b3'
end

But I'm getting:

/home/user/Documents/Projects/imodule/config/initializers/imodule.rb:2:in <top (required)>': undefined methodconfigure' for Imodule:Module (NoMethodError)


Solution

  • There's nothing wrong with the code you posted, only if the the code in lib/imodule/imodule.rb is not being loaded before it's called in config/initializers/imodule.rb.

    It looks like this is in a Rails app called imodule, so Imodule is defined as the app module, explaining why you would have just a NoMethodError instead of a NameError when your module code isn't loaded.

    Rails doesn't automatically require files in your lib directory, so adding require 'imodule/imodule' at the top of the file will fix the problem.