跳至內容 跳至搜尋

有序選項

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 64
def extractable_options?
  true
end

inspect()

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

method_missing(method, *args)

# File activesupport/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