有序选项
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
源代码:显示 | 在 GitHub 上
# File activesupport/lib/active_support/ordered_options.rb, line 41 def [](key) super(key.to_sym) end
[]=(key, value) 链接
源代码:显示 | 在 GitHub 上
# File activesupport/lib/active_support/ordered_options.rb, line 37 def []=(key, value) super(key.to_sym, value) end
dig(key, *identifiers) 链接
源代码:显示 | 在 GitHub 上
# File activesupport/lib/active_support/ordered_options.rb, line 45 def dig(key, *identifiers) super(key.to_sym, *identifiers) end
extractable_options?() 链接
来源:显示 | 在 GitHub 上
# File activesupport/lib/active_support/ordered_options.rb, line 68 def extractable_options? true end
inspect() 链接
来源:显示 | 在 GitHub 上
# File activesupport/lib/active_support/ordered_options.rb, line 72 def inspect "#<#{self.class.name} #{super}>" end
method_missing(name, *args) 链接
来源:显示 | 在 GitHub 上
# 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) 链接
来源:显示 | 在 GitHub 上
# File activesupport/lib/active_support/ordered_options.rb, line 64 def respond_to_missing?(name, include_private) true end