File: module_inheritable_attributes.rb

package info (click to toggle)
ruby-httparty 0.24.2-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 964 kB
  • sloc: ruby: 7,521; xml: 425; sh: 35; makefile: 14
file content (56 lines) | stat: -rw-r--r-- 1,510 bytes parent folder | download
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
# frozen_string_literal: true

module HTTParty
  module ModuleInheritableAttributes #:nodoc:
    def self.included(base)
      base.extend(ClassMethods)
    end

    # borrowed from Rails 3.2 ActiveSupport
    def self.hash_deep_dup(hash)
      duplicate = hash.dup

      duplicate.each_pair do |key, value|
        if value.is_a?(Hash)
          duplicate[key] = hash_deep_dup(value)
        elsif value.is_a?(Proc)
          duplicate[key] = value.dup
        else
          duplicate[key] = value
        end
      end

      duplicate
    end

    module ClassMethods #:nodoc:
      def mattr_inheritable(*args)
        @mattr_inheritable_attrs ||= [:mattr_inheritable_attrs]
        @mattr_inheritable_attrs += args

        args.each do |arg|
          singleton_class.attr_accessor(arg)
        end

        @mattr_inheritable_attrs
      end

      def inherited(subclass)
        super
        @mattr_inheritable_attrs.each do |inheritable_attribute|
          ivar = :"@#{inheritable_attribute}"
          subclass.instance_variable_set(ivar, instance_variable_get(ivar).clone)

          if instance_variable_get(ivar).respond_to?(:merge)
            subclass.class_eval <<~RUBY, __FILE__, __LINE__ + 1
              def self.#{inheritable_attribute}
                duplicate = ModuleInheritableAttributes.hash_deep_dup(#{ivar})
                #{ivar} = superclass.#{inheritable_attribute}.merge(duplicate)
              end
            RUBY
          end
        end
      end
    end
  end
end