跳至内容 跳至搜索

有序选项

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

respond_to_missing?(name, include_private)

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