Module: CoreExtensions::Hash::Parameters
- Included in:
- Hash
- Defined in:
- lib/hash_args.rb
Overview
Allows a Hash to more easily be used to pass arguments to methods.
Instance Method Summary collapse
-
#fetch_arg(key, default = nil, opts = {}, &block) ⇒ Object
Works like Hash#fetch with 2 additions.
- #fetch_arg_array(key, default = nil, opts = {}, &block) ⇒ Object
Instance Method Details
#fetch_arg(key, default = nil, opts = {}, &block) ⇒ Object
Works like Hash#fetch with 2 additions. It will optionally treat nil like a missing key (that’s the default). It will also allow the caller to require a parameter or it will raise an exception.
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
# File 'lib/hash_args.rb', line 6 def fetch_arg(key, default = nil, opts = {}, &block) if opts[:required] == true raise ArgumentError, "#{key.to_s.capitalize} required." if not has_key? key end if not default.nil? or block.nil? ret = fetch key, default else ret = fetch key, &block end if ret == nil and opts[:ignore_nil] != true if opts[:required] == true raise ArgumentError, "#{key.to_s.capitalize} required." end if not block.nil? ret = block.call(key) else ret = default end end if opts[:array] == true and not ret.is_a? Array ret = [ret] end ret end |
#fetch_arg_array(key, default = nil, opts = {}, &block) ⇒ Object
36 37 38 39 |
# File 'lib/hash_args.rb', line 36 def fetch_arg_array(key, default = nil, opts = {}, &block) opts.merge!(:array => true) fetch_arg(key, default, opts, &block) end |