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: :dog is blank
Methods
Instance Public methods
[](key)
Also aliased as: _get
📝 Source code
# File activesupport/lib/active_support/ordered_options.rb, line 37
def [](key)
super(key.to_sym)
end
🔎 See on GitHub
[]=(key, value)
📝 Source code
# File activesupport/lib/active_support/ordered_options.rb, line 33
def []=(key, value)
super(key.to_sym, value)
end
🔎 See on GitHub
method_missing(name, *args)
📝 Source code
# File activesupport/lib/active_support/ordered_options.rb, line 41
def method_missing(name, *args)
name_string = name.to_s.dup
if name_string.chomp!("=")
self[name_string] = args.first
else
bangs = name_string.chomp!("!")
if bangs
self[name_string].presence || raise(KeyError.new(":#{name_string} is blank"))
else
self[name_string]
end
end
end
🔎 See on GitHub
respond_to_missing?(name, include_private)
📝 Source code
# File activesupport/lib/active_support/ordered_options.rb, line 56
def respond_to_missing?(name, include_private)
true
end
🔎 See on GitHub