Sha256: bf4a08bb17c2edae4eaeba3135b5eca550a886c492b7af53b41516114b3efce0

Contents?: true

Size: 883 Bytes

Versions: 3

Compression:

Stored size: 883 Bytes

Contents

require 'facets/module/class_extend'

class Module

  # Like #class_inheritor but non-dynamic. The value of the inheritor
  # is copied from the ancestor on first read.
  #
  #   c = Class.new do
  #     def self.x; ['x']; end
  #   end
  #
  #   d = Class.new(c) do
  #     copy_inheritor :x
  #   end
  #
  #   d.x  #=> ['x']
  #
  # CREDIT: Thomas Sawyer

  def copy_inheritor(name, default={})
    class_extend do
      define_method(name) do
        if instance_variable_defined?("@#{name}")
          instance_variable_get("@#{name}")
        else
          if anc = ancestors[1..-1].find{ |a| a.respond_to?(name) }
            value = anc.__send__(name)
            value = value.dup rescue value
            instance_variable_set("@#{name}", value)
          else
            instance_variable_set("@#{name}", default)
          end
        end
      end
    end
  end

end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
facets-2.9.0 lib/tour/facets/module/copy_inheritor.rb
facets-2.9.0.pre.2 lib/tour/facets/module/copy_inheritor.rb
facets-2.9.0.pre.1 lib/tour/facets/module/copy_inheritor.rb