Class: ActiveSupport::OrderedOptions

Inherits:
Hash show all
Defined in:
lib/active_support/ordered_options.rb

Overview

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

Direct Known Subclasses

InheritableOptions

Instance Method Summary collapse

Methods inherited from Hash

#as_json, #assert_valid_keys, #compact, #compact!, #deep_dup, #deep_merge, #deep_merge!, #deep_stringify_keys, #deep_stringify_keys!, #deep_symbolize_keys, #deep_symbolize_keys!, #deep_transform_keys, #deep_transform_keys!, #except, #except!, #extract!, #extractable_options?, from_trusted_xml, from_xml, #reverse_merge, #reverse_merge!, #slice, #slice!, #stringify_keys, #stringify_keys!, #symbolize_keys, #symbolize_keys!, #to_query, #to_xml, #transform_keys, #transform_keys!, #transform_values, #transform_values!, #with_indifferent_access

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File '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

Instance Method Details

#[](key) ⇒ Object



35
36
37
# File 'lib/active_support/ordered_options.rb', line 35

def [](key)
  super(key.to_sym)
end

#[]=(key, value) ⇒ Object



31
32
33
# File 'lib/active_support/ordered_options.rb', line 31

def []=(key, value)
  super(key.to_sym, value)
end

#respond_to_missing?(name, include_private) ⇒ Boolean

Returns:

  • (Boolean)


54
55
56
# File 'lib/active_support/ordered_options.rb', line 54

def respond_to_missing?(name, include_private)
  true
end