Usually key value pairs are handled something like this:
h = {}
h[:boy] = 'John'
h[:girl] = 'Mary'
h[:boy] # => 'John'
h[:girl] # => 'Mary'
h[:dog] # => nil
Using OrderedOptions
, the above code could be reduced to:
h = ActiveSupport::OrderedOptions.new
h.boy = 'John'
h.girl = 'Mary'
h.boy # => 'John'
h.girl # => 'Mary'
h.dog # => nil
To raise an exception when the value is blank, append a bang to the key name, like:
h.dog! # => raises KeyError: key not found: :dog
Methods
- #
- M
- R
Instance Public methods
[]=(key, value)
Link
method_missing(name, *args)
Link
# File activesupport/lib/active_support/ordered_options.rb, line 39 def method_missing(name, *args) name_string = name.to_s if name_string.chomp!("=") self[name_string] = args.first else bangs = name_string.chomp!("!") if bangs fetch(name_string.to_sym).presence || raise(KeyError.new("#{name_string} is blank.")) else self[name_string] end end end