Where to place/access config file in gem?

I’m jumping on this one a little late but I’ll leave an example implementation of how I generally handle this, for future reference.

As it was mentioned, you’ll normally want to allow configuration through both files and hashes. It’s pretty easy and light to include both ways, so you should do it.

Something like this works for me in most scenarios:

require 'yaml'

module MyGem
  # Configuration defaults
  @config = {
              :log_level => "verbose",
              :min => 0,
              :max => 99 
            }

  @valid_config_keys = @config.keys

  # Configure through hash
  def self.configure(opts = {})
    opts.each {|k,v| @config[k.to_sym] = v if @valid_config_keys.include? k.to_sym}
  end

  # Configure through yaml file
  def self.configure_with(path_to_yaml_file)
    begin
      config = YAML::load(IO.read(path_to_yaml_file))
    rescue Errno::ENOENT
      log(:warning, "YAML configuration file couldn't be found. Using defaults."); return
    rescue Psych::SyntaxError
      log(:warning, "YAML configuration file contains invalid syntax. Using defaults."); return
    end

    configure(config)
  end

  def self.config
    @config
  end
end

An added best practice would be to have defaults for all your configuration keys(as in the example above). That way, you are giving the user ultimate freedom in how they can configure your library.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)