Class: WavefrontCli::OptHandler
- Inherits:
-
Object
- Object
- WavefrontCli::OptHandler
- Includes:
- Constants
- Defined in:
- lib/wavefront-cli/opt_handler.rb
Overview
Options to commands can come from three sources, with the following order of precedence: program defaults, a configuration file, and command-line options. Docopt is not well suited to this, as it will “fill in” any missing options with defaults, producing a single hash which must be merged with values from the config file. Assuming we give the command-line higher precedence, a default value, not supplied by the user, will override a value in the config file. The other way round, and you can’t override anything in the config file from the command-line. I think this behaviour is far from unique to Docopt.
So, we have a hash of defaults, and we do the merging ourselves, in this class. We trick Docopt into not using the defaults by avoiding the magic string ‘default: ’ in our options stanzas.
Constant Summary
Constants included from Constants
Constants::DEFAULT_OPTS, Constants::HUMAN_TIME_FORMAT, Constants::HUMAN_TIME_FORMAT_MS
Instance Attribute Summary collapse
-
#opts ⇒ Object
readonly
Returns the value of attribute opts.
Instance Method Summary collapse
-
#initialize(cli_opts = {}) ⇒ OptHandler
constructor
A new instance of OptHandler.
-
#load_profile(cred_opts) ⇒ Hash
Load credentials (and other config) using the SDK Credentials class.
-
#setup_cred_opts(cli_opts) ⇒ Hash
Create an options hash to pass to the Wavefront::Credentials constructor.
Constructor Details
#initialize(cli_opts = {}) ⇒ OptHandler
Returns a new instance of OptHandler.
29 30 31 32 33 |
# File 'lib/wavefront-cli/opt_handler.rb', line 29 def initialize(cli_opts = {}) cred_opts = setup_cred_opts(cli_opts) cli_opts.reject! { |_k, v| v.nil? } @opts = DEFAULT_OPTS.merge(load_profile(cred_opts)).merge(cli_opts) end |
Instance Attribute Details
#opts ⇒ Object (readonly)
Returns the value of attribute opts.
27 28 29 |
# File 'lib/wavefront-cli/opt_handler.rb', line 27 def opts @opts end |
Instance Method Details
#load_profile(cred_opts) ⇒ Hash
Load credentials (and other config) using the SDK Credentials class. This allows the user to override values with environment variables
65 66 67 68 |
# File 'lib/wavefront-cli/opt_handler.rb', line 65 def load_profile(cred_opts) creds = Wavefront::Credentials.new(cred_opts).config Hash[creds.map{ |k, v| [k.to_sym, v] }] end |
#setup_cred_opts(cli_opts) ⇒ Hash
Create an options hash to pass to the Wavefront::Credentials constructor.
42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
# File 'lib/wavefront-cli/opt_handler.rb', line 42 def setup_cred_opts(cli_opts) cred_opts = {} if cli_opts[:config] cred_opts[:file] = Pathname.new(cli_opts[:config]) unless cred_opts[:file].exist? puts "config file '#{cred_opts[:file]}' not found." end end cred_opts[:profile] = cli_opts[:profile] if cli_opts[:profile] cred_opts end |