Sha256: 97da971d34a1915a6099feeb5357d07669cc03b3f7bb958d5e0e3ab11711d515

Contents?: true

Size: 1.88 KB

Versions: 1

Compression:

Stored size: 1.88 KB

Contents

require 'thread'
require "heredity/version"

module Heredity
  module InheritableClassInstanceVariables
    def self.included(klass)
      Thread.exclusive do
        klass.extend(::Heredity::InheritableClassInstanceVariables::ClassMethods)

        klass.class_eval do
          @_inheritable_class_instance_variables = [ :_inheritable_class_instance_variables ]

          class << self
            alias_method :inheritable_attribute, :inheritable_attributes
            alias_method :class_inheritable_attributes, :inheritable_attributes
            alias_method :class_inheritable_attribute, :inheritable_attributes
          end
        end
      end
    end

    module ClassMethods
      def inheritable_attributes(*args)
        Thread.exclusive do
          args.flatten.compact.uniq.each do |class_instance_variable|
            unless @_inheritable_class_instance_variables.include?(class_instance_variable)
              @_inheritable_class_instance_variables << class_instance_variable
            end
          end

          @_inheritable_class_instance_variables.each do |attr_symbol|
            unless self.respond_to?("#{attr_symbol}")
              class_eval %Q{
                class << self; attr_reader :#{attr_symbol}; end
              }
            end

            unless self.respond_to?("#{attr_symbol}=")
              class_eval %Q{
                class << self; attr_writer :#{attr_symbol}; end
              }
            end
          end

          @_inheritable_class_instance_variables
        end
      end

      def inherited(klass)
        super # ActiveRecord needs the inherited hook to setup fields

        Thread.exclusive do
          @_inheritable_class_instance_variables.each do |attribute|
            attr_sym = :"@#{attribute}"
            klass.instance_variable_set(attr_sym, self.instance_variable_get(attr_sym))
          end
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
heredity-0.0.1 lib/heredity.rb