Sha256: 1f1ae7e45b4312bc78e9dcbf67c510983c6a9f4d77c9e1f880ac06f3b7ddd77d

Contents?: true

Size: 1.69 KB

Versions: 16

Compression:

Stored size: 1.69 KB

Contents

begin
  require 'active_support/core_ext/class/attribute'
rescue LoadError
  module Kernel
    # Returns the object's singleton class.
    def singleton_class
      class << self
        self
      end
    end unless respond_to?(:singleton_class) # exists in 1.9.2

    # class_eval on an object acts like singleton_class.class_eval.
    def class_eval(*args, &block)
      singleton_class.class_eval(*args, &block)
    end
  end

  class Module
    def remove_possible_method(method)
      if method_defined?(method) || private_method_defined?(method)
        remove_method(method)
      end
    rescue NameError
      # If the requested method is defined on a superclass or included module,
      # method_defined? returns true but remove_method throws a NameError.
      # Ignore this.
    end

    def redefine_method(method, &block)
      remove_possible_method(method)
      define_method(method, &block)
    end
  end

  class Class
    def class_attribute(*attrs)
      attrs.each do |name|
        class_eval <<-RUBY, __FILE__, __LINE__ + 1
          def self.#{name}() nil end
          def self.#{name}?() !!#{name} end

          def self.#{name}=(val)
            singleton_class.class_eval do
              remove_possible_method(:#{name})
              define_method(:#{name}) { val }
            end

            if singleton_class?
              class_eval do
                remove_possible_method(:#{name})
                def #{name}
                  defined?(@#{name}) ? @#{name} : singleton_class.#{name}
                end
              end
            end
            val
          end
        RUBY

      end
    end

    private
    def singleton_class?
      ancestors.first != self
    end
  end
end

Version data entries

16 entries across 16 versions & 2 rubygems

Version Path
oat-0.5.1 lib/support/class_attribute.rb
oat-0.5.0 lib/support/class_attribute.rb
oat-0.4.7 lib/support/class_attribute.rb
oat-0.4.6 lib/support/class_attribute.rb
parametric-0.0.5 lib/support/class_attribute.rb
oat-0.4.5 lib/support/class_attribute.rb
oat-0.4.4 lib/support/class_attribute.rb
oat-0.4.3 lib/support/class_attribute.rb
oat-0.4.2 lib/support/class_attribute.rb
oat-0.4.1 lib/support/class_attribute.rb
oat-0.4.0 lib/support/class_attribute.rb
oat-0.3.0 lib/support/class_attribute.rb
oat-0.2.5 lib/support/class_attribute.rb
oat-0.2.4 lib/support/class_attribute.rb
oat-0.2.3 lib/support/class_attribute.rb
oat-0.2.2 lib/support/class_attribute.rb