summaryrefslogtreecommitdiff
path: root/lib/hashie/extensions/dash/indifferent_access.rb
blob: 204cae6d0ab186f9b6fce4d7f3616108e3cfd411 (plain)
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
module Hashie
  module Extensions
    module Dash
      module IndifferentAccess
        def self.included(base)
          base.extend ClassMethods
          base.send :include, Hashie::Extensions::IndifferentAccess
        end

        def self.maybe_extend(base)
          return unless requires_class_methods?(base)

          base.extend(ClassMethods)
        end

        def self.requires_class_methods?(klass)
          klass <= Hashie::Dash &&
            !klass.singleton_class.included_modules.include?(ClassMethods)
        end
        private_class_method :requires_class_methods?

        module ClassMethods
          # Check to see if the specified property has already been
          # defined.
          def property?(name)
            name = translations[name.to_sym] if translation_for?(name)
            name = name.to_s
            !!properties.find { |property| property.to_s == name }
          end

          def translation_exists?(name)
            name = name.to_s
            !!translations.keys.find { |key| key.to_s == name }
          end

          def transformed_property(property_name, value)
            transform = transforms[property_name] || transforms[property_name.to_sym]
            transform.call(value)
          end

          def transformation_exists?(name)
            name = name.to_s
            !!transforms.keys.find { |key| key.to_s == name }
          end

          private

          def translation_for?(name)
            included_modules.include?(Hashie::Extensions::Dash::PropertyTranslation) &&
              translation_exists?(name)
          end
        end
      end
    end
  end
end