Class: ActiveSupport::OrderedOptions

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

Overview

Ordered Options

OrderedOptions inherits from Hash and provides dynamic accessor methods.

With a Hash, key-value pairs are typically managed like this:

h = {}
h[:boy] = 'John'
h[:girl] = 'Mary'
h[:boy]  # => 'John'
h[:girl] # => 'Mary'
h[:dog]  # => nil

Using OrderedOptions, the above code can be written as:

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

Direct Known Subclasses

InheritableOptions

Instance Method Summary collapse

Methods inherited from Hash

#as_json, #assert_valid_keys, #compact_blank, #compact_blank!, #deep_dup, #deep_merge?, #deep_stringify_keys, #deep_stringify_keys!, #deep_symbolize_keys, #deep_symbolize_keys!, #deep_transform_keys, #deep_transform_keys!, #deep_transform_values, #deep_transform_values!, #except!, #extract!, from_trusted_xml, from_xml, #present?, #reverse_merge, #reverse_merge!, #slice!, #stringify_keys, #stringify_keys!, #symbolize_keys, #symbolize_keys!, #to_query, #to_xml, #with_indifferent_access

Methods included from DeepMergeable

#deep_merge, #deep_merge!, #deep_merge?

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args) ⇒ Object



49
50
51
52
53
54
55
56
57
58
# File 'lib/active_support/ordered_options.rb', line 49

def method_missing(method, *args)
  if method.end_with?("=")
    self[method.name.chomp("=")] = args.first
  elsif method.end_with?("!")
    name_string = method.name.chomp("!")
    self[name_string].presence || raise(KeyError.new(":#{name_string} is blank"))
  else
    self[method.name]
  end
end

Instance Method Details

#[](key) ⇒ Object



41
42
43
# File 'lib/active_support/ordered_options.rb', line 41

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

#[]=(key, value) ⇒ Object



37
38
39
# File 'lib/active_support/ordered_options.rb', line 37

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

#dig(key, *identifiers) ⇒ Object



45
46
47
# File 'lib/active_support/ordered_options.rb', line 45

def dig(key, *identifiers)
  super(key.to_sym, *identifiers)
end

#extractable_options?Boolean

Returns:

  • (Boolean)


64
65
66
# File 'lib/active_support/ordered_options.rb', line 64

def extractable_options?
  true
end

#inspectObject



68
69
70
# File 'lib/active_support/ordered_options.rb', line 68

def inspect
  "#<#{self.class.name} #{super}>"
end

#respond_to_missing?(name, include_private) ⇒ Boolean

Returns:

  • (Boolean)


60
61
62
# File 'lib/active_support/ordered_options.rb', line 60

def respond_to_missing?(name, include_private)
  true
end