2012-09-17 01:22:18 -04:00
|
|
|
module ActiveSupport
|
2012-09-17 01:12:11 -04:00
|
|
|
# Usually key value pairs are handled something like this:
|
|
|
|
#
|
|
|
|
# h = {}
|
|
|
|
# h[:boy] = 'John'
|
|
|
|
# h[:girl] = 'Mary'
|
|
|
|
# h[:boy] # => 'John'
|
|
|
|
# h[:girl] # => 'Mary'
|
|
|
|
#
|
2012-09-17 01:22:18 -04:00
|
|
|
# Using +OrderedOptions+, the above code could be reduced to:
|
2012-09-17 01:12:11 -04:00
|
|
|
#
|
|
|
|
# h = ActiveSupport::OrderedOptions.new
|
|
|
|
# h.boy = 'John'
|
|
|
|
# h.girl = 'Mary'
|
|
|
|
# h.boy # => 'John'
|
|
|
|
# h.girl # => 'Mary'
|
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
|
|
|
|
2012-05-05 02:24:57 -04:00
|
|
|
def respond_to_missing?(name, include_private)
|
2011-06-14 01:45:34 -04:00
|
|
|
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
|