I\'m writing a gem which I would like to work with and without the Rails environment.
I have a Configuration
class to allow configuration of the gem:
The main issue is that you've applied too much indirection. Why don't you just do
module NameChecker
class << self
attr_accessor :api_key, :log_level
end
end
and be done with it? You could also override the two generated readers right afterwards so that they ensure the presence of the environment that you need...
module NameChecker
class << self
attr_accessor :api_key, :log_level
def api_key
raise "NameChecker really needs is't api_key set to work" unless @api_key
@api_key
end
DEFAULT_LOG_LEVEL = 'info'
def log_level
@log_level || DEFAULT_LOG_LEVEL
end
end
end
Now, the actual (technical) problem is that you are defining a class called NetChecker
and while defining it you are trying to print the return value of the api_key
call on an assumed Configuration
object (so you are violating the law of Demeter here). This fails, because you are defining NetChecker
before anyone really has had time to define any configuration. So you are in fact requesting api_key
before the configure
method has been called on NameChecker
, so it has nil
in it's configuration
ivar.
My advice would be to remove the overengineering and try again ;-)
Try refactoring to:
def self.configuration
@configuration ||= Configuration.new
end
def self.configure
yield(configuration) if block_given?
end