Module: Mongoid::Extensions::Hash::IndifferentAccess

Defined in:
lib/mongoid_indifferent_access.rb

Constant Summary collapse

VERSION =
"1.0.0"

Class Method Summary collapse

Class Method Details

.included(klass) ⇒ Object



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
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/mongoid_indifferent_access.rb', line 8

def self.included(klass)
  klass.class_eval do

    def self.field(name, options={})
      field = super(name, options)

      if options[:type] && options[:type].name == 'Hash'
        getter_name = name.to_sym
        setter_name = "#{getter_name}=".to_sym

        hia_define_getter(getter_name, setter_name)
        hia_define_setter(setter_name)

        descendants.each do |subclass|
          subclass.hia_define_getter(getter_name, setter_name)
          subclass.hia_define_setter(setter_name)
        end
      end

      field
    end

    def self.hia_define_getter(getter_name, setter_name)
      define_method(getter_name) do
        val = super()
        unless val.nil? || val.is_a?(HashWithIndifferentAccess)
          wrapped_hash = val.with_indifferent_access
          self.send(setter_name, wrapped_hash) unless self.frozen?
          val = wrapped_hash
        end
        val
      end
    end

    def self.hia_define_setter(setter_name)
      define_method(setter_name) do |hash|
        unless hash.nil? || hash.is_a?(HashWithIndifferentAccess)
          hash = hash.with_indifferent_access
        end
        super(hash)
      end
    end

  end
end