跳到內容 跳到搜尋

Ordered Options

OrderedOptions 繼承自 Hash 並提供動態存取方法。

使用 Hash,通常會這樣管理鍵值對

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

使用 OrderedOptions,以上的程式碼可以寫成

h = ActiveSupport::OrderedOptions.new
h.boy = 'John'
h.girl = 'Mary'
h.boy  # => 'John'
h.girl # => 'Mary'
h.dog  # => nil

如果值為空白時要引發例外,請在金鑰名稱後加上驚嘆號,例如

h.dog! # => raises KeyError: :dog is blank
方法
#
D
E
I
M
R

實例公開方法

[](key)

別名: _get
# File activesupport/lib/active_support/ordered_options.rb, line 41
def [](key)
  super(key.to_sym)
end

[]=(key, value)

# File activesupport/lib/active_support/ordered_options.rb, line 37
def []=(key, value)
  super(key.to_sym, value)
end

_get(key)

別名: []

dig(key, *identifiers)

# File activesupport/lib/active_support/ordered_options.rb, line 45
def dig(key, *identifiers)
  super(key.to_sym, *identifiers)
end

extractable_options?()

# File activesupport/lib/active_support/ordered_options.rb, line 68
def extractable_options?
  true
end

inspect()

# File activesupport/lib/active_support/ordered_options.rb, line 72
def inspect
  "#<#{self.class.name} #{super}>"
end

method_missing(name, *args)

# File activesupport/lib/active_support/ordered_options.rb, line 49
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
      self[name_string].presence || raise(KeyError.new(":#{name_string} is blank"))
    else
      self[name_string]
    end
  end
end

respond_to_missing?(name, include_private)

# File activesupport/lib/active_support/ordered_options.rb, line 64
def respond_to_missing?(name, include_private)
  true
end