Sha256: 983860da893b73f5f3b75960f0bde60cd47708f3a879a4c8c068f4906d0efaba

Contents?: true

Size: 1.22 KB

Versions: 16

Compression:

Stored size: 1.22 KB

Contents

module Representable
  # Objects marked cloneable will be cloned in #inherit!.
  module Cloneable
  end

  # Objects marked cloneable will be inherit!ed in #inherit! when available in parent and child.
  module Inheritable
    include Cloneable # all Inheritable are also Cloneable since #clone is one step of our inheritance.

    class Array < ::Array
      include Inheritable

      def inherit!(parent)
        push(*parent.clone)
      end
    end

    class Hash < ::Hash
      include Inheritable

      module InstanceMethods
        def inherit!(parent)
          #merge!(parent.clone)
          for key in (parent.keys + keys).uniq
            next unless parent_value = parent[key]

            self[key].inherit!(parent_value) and next if self[key].is_a?(Inheritable)
            self[key] = parent_value.clone and next if parent_value.is_a?(Cloneable)

            self[key] = parent_value # merge! behaviour
          end

          self
        end

        def clone
          self.class[ collect { |k,v| [k, clone_value(v)] } ]
        end

      private
        def clone_value(value)
          return value.clone if value.is_a?(Cloneable)
          value
        end
      end

      include InstanceMethods
    end
  end
end

Version data entries

16 entries across 16 versions & 1 rubygems

Version Path
representable-2.2.0 lib/representable/inheritable.rb
representable-2.1.8 lib/representable/inheritable.rb
representable-2.1.7 lib/representable/inheritable.rb
representable-2.1.6 lib/representable/inheritable.rb
representable-2.1.5 lib/representable/inheritable.rb
representable-2.1.4 lib/representable/inheritable.rb
representable-2.1.3 lib/representable/inheritable.rb
representable-2.1.1 lib/representable/inheritable.rb
representable-2.1.0 lib/representable/inheritable.rb
representable-2.0.4 lib/representable/inheritable.rb
representable-2.0.3 lib/representable/inheritable.rb
representable-2.0.2 lib/representable/inheritable.rb
representable-2.0.1 lib/representable/inheritable.rb
representable-2.0.0 lib/representable/inheritable.rb
representable-2.0.0.rc2 lib/representable/inheritable.rb
representable-2.0.0.rc1 lib/representable/inheritable.rb