2010-08-06 01:50:54 -04:00
|
|
|
# Usually key value pairs are handled something like this:
|
2010-08-14 01:13:00 -04:00
|
|
|
#
|
2011-02-27 20:22:55 -05:00
|
|
|
# h = {}
|
2010-08-06 01:50:54 -04:00
|
|
|
# h[:boy] = 'John'
|
|
|
|
# h[:girl] = 'Mary'
|
2010-08-06 07:11:44 -04:00
|
|
|
# h[:boy] # => 'John'
|
|
|
|
# h[:girl] # => 'Mary'
|
2010-08-14 01:13:00 -04:00
|
|
|
#
|
2011-02-27 20:22:55 -05:00
|
|
|
# Using <tt>OrderedOptions</tt>, the above code could be reduced to:
|
2010-08-06 01:50:54 -04:00
|
|
|
#
|
|
|
|
# h = ActiveSupport::OrderedOptions.new
|
|
|
|
# h.boy = 'John'
|
|
|
|
# h.girl = 'Mary'
|
2010-08-06 07:11:44 -04:00
|
|
|
# h.boy # => 'John'
|
|
|
|
# h.girl # => 'Mary'
|
2010-08-14 01:13:00 -04:00
|
|
|
#
|
2008-06-03 14:32:53 -04:00
|
|
|
module ActiveSupport #:nodoc:
|
2012-02-21 12:38:36 -05:00
|
|
|
class OrderedOptions < Hash
|
2010-09-27 08:48:06 -04:00
|
|
|
alias_method :_get, :[] # preserve the original #[] method
|
|
|
|
protected :_get # make it protected
|
|
|
|
|
2008-06-03 14:32:53 -04:00
|
|
|
def []=(key, value)
|
|
|
|
super(key.to_sym, value)
|
|
|
|
end
|
2006-05-31 18:43:53 -04:00
|
|
|
|
2008-06-03 14:32:53 -04:00
|
|
|
def [](key)
|
|
|
|
super(key.to_sym)
|
|
|
|
end
|
2006-02-25 18:06:04 -05:00
|
|
|
|
2008-06-03 14:32:53 -04:00
|
|
|
def method_missing(name, *args)
|
2012-01-21 05:15:08 -05:00
|
|
|
name_string = name.to_s
|
|
|
|
if name_string.chomp!('=')
|
|
|
|
self[name_string] = args.first
|
2008-06-03 14:32:53 -04:00
|
|
|
else
|
|
|
|
self[name]
|
|
|
|
end
|
2006-02-25 18:06:04 -05:00
|
|
|
end
|
2011-06-14 01:45:34 -04:00
|
|
|
|
|
|
|
def respond_to?(name)
|
|
|
|
true
|
|
|
|
end
|
2006-02-25 18:06:04 -05:00
|
|
|
end
|
2010-03-02 20:18:01 -05:00
|
|
|
|
|
|
|
class InheritableOptions < OrderedOptions
|
2010-09-27 08:51:31 -04:00
|
|
|
def initialize(parent = nil)
|
2010-09-27 08:48:06 -04:00
|
|
|
if parent.kind_of?(OrderedOptions)
|
|
|
|
# use the faster _get when dealing with OrderedOptions
|
|
|
|
super() { |h,k| parent._get(k) }
|
|
|
|
elsif parent
|
2010-09-27 08:51:31 -04:00
|
|
|
super() { |h,k| parent[k] }
|
|
|
|
else
|
|
|
|
super()
|
|
|
|
end
|
2010-03-02 20:18:01 -05:00
|
|
|
end
|
2010-09-27 08:50:39 -04:00
|
|
|
|
|
|
|
def inheritable_copy
|
|
|
|
self.class.new(self)
|
|
|
|
end
|
2010-03-02 20:18:01 -05:00
|
|
|
end
|
2006-05-31 18:43:53 -04:00
|
|
|
end
|