Ruby on Rails | Screencasts | Download | Documentation | Weblog | Community | Source

root/trunk/activesupport/lib/active_support/ordered_options.rb

Revision 8974, 1.0 kB (checked in by nzkoz, 6 months ago)

Add OrderedHash#to_hash. Closes #11266 [josh]

Line 
1 # OrderedHash is namespaced to prevent conflicts with other implementations
2 module ActiveSupport
3   # Hash is ordered in Ruby 1.9!
4   if RUBY_VERSION >= '1.9'
5     OrderedHash = ::Hash
6   else
7     class OrderedHash < Array #:nodoc:
8       def []=(key, value)
9         if pair = assoc(key)
10           pair.pop
11           pair << value
12         else
13           self << [key, value]
14         end
15       end
16
17       def [](key)
18         pair = assoc(key)
19         pair ? pair.last : nil
20       end
21
22       def keys
23         collect { |key, value| key }
24       end
25
26       def values
27         collect { |key, value| value }
28       end
29
30       def to_hash
31         returning({}) do |hash|
32           each { |array| hash[array[0]] = array[1] }
33         end
34       end
35     end
36   end
37 end
38
39 class OrderedOptions < ActiveSupport::OrderedHash #:nodoc:
40   def []=(key, value)
41     super(key.to_sym, value)
42   end
43
44   def [](key)
45     super(key.to_sym)
46   end
47
48   def method_missing(name, *args)
49     if name.to_s =~ /(.*)=$/
50       self[$1.to_sym] = args.first
51     else
52       self[name]
53     end
54   end
55 end
Note: See TracBrowser for help on using the browser.