File: flexible_hash.rb

package info (click to toggle)
ruby-ice-cube 0.16.4-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 800 kB
  • sloc: ruby: 7,823; makefile: 6
file content (40 lines) | stat: -rw-r--r-- 760 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
require 'delegate'

module IceCube

  # Find keys by symbol or string without symbolizing user input
  # Due to the serialization format of ice_cube, this limited implementation
  # is entirely sufficient

  class FlexibleHash < SimpleDelegator

    def [](key)
      key = _match_key(key)
      super
    end

    def fetch(key)
      key = _match_key(key)
      super
    end

    def delete(key)
      key = _match_key(key)
      super
    end

    private

    def _match_key(key)
      return key if __getobj__.has_key? key
      if Symbol == key.class
        __getobj__.keys.detect { |k| return k if k == key.to_s }
      elsif String == key.class
        __getobj__.keys.detect { |k| return k if k.to_s == key }
      end
      key
    end

  end

end