Skip to content

Instantly share code, notes, and snippets.

@richievos
Created November 28, 2012 05:28
Show Gist options
  • Save richievos/4159201 to your computer and use it in GitHub Desktop.
Save richievos/4159201 to your computer and use it in GitHub Desktop.

The use case is a command line tool that needs some configuration. The simplest case is just reading in a yml file for it, but commonly people have more complicated ways of doing this configuration (a hierarchy of configs that get merged, or some environment sourced things, or an erb yml file, or ...) so I also want to be able to let people set a pre-processed config.

The original command line was going to be:

  background_job_kicker_offer -c path_to_config_file -r any_file_you_want_required -r some_other_file start

Most of these solutions will leverage the -r option to allow for complex ruby to run.

Option 1: make people set config in one of their initializers

This relies upon some people setting a config somehow. It could use a constant or something (just assume the constant is named X), but doing something like a BackgroundJobThing.default_config=(config) setter seems simple.

Usage:

  background_job_kicker_offer -r config/environment.rb

In the library:

  module BackgroundJobKickerOffer
    def self.default_config=(default_config)
      @default_config = default_config
    end

  ...
  configuration = config_file_if_passed || BackgroundJobKickerOffer.default_config

config/initializers/background_job_kicker_offer.rb

  BackgroundJobKickerOffer.default_config = Settings.background_job_kicker_offer_config

Pros:

  • pretty straightforward
Cons:
  • need to create this config setter/getter which isn't otherwise used except for being a spot for this "global" to get jammed

Option 2: let people specify how to 'source' the config

Usage:

  background_job_kicker_offer -r config/environment.rb --config_eval="Settings.background_job_kicker_offer_config"

Other suggestions for the argument name:

  • -e -- ala ruby -e
  • -c -- first try -c as a file, then fallback to eval'ing it (this seems dangerous)
In the library:

  configuration = config_file_if_passed || (eval(config_eval_argument) if config_eval_argument_passed?)

Pros:

  • Easy, doesn't require dumping anything in a ruby file
Cons:
  • Uses eval

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment