Sha256: 0e1dcc8ae4c1da904f5de507c228ec61d9b704c0ed179203bccfa5ff26e86b96

Contents?: true

Size: 1.59 KB

Versions: 2

Compression:

Stored size: 1.59 KB

Contents

# frozen_string_literal: true

unless defined?(Rails) || defined?(ActiveSupport)
  # See {Class}
  # @api private
  class Class
    # @api private
    def class_attribute(*attrs)
      options       = attrs.extract_options!
      default_value = options.fetch(:default, nil)

      attrs.each do |name|
        singleton_class.silence_redefinition_of_method(name)
        define_singleton_method(name) { nil }

        singleton_class.silence_redefinition_of_method("#{name}?")
        define_singleton_method("#{name}?") { !!public_send(name) }

        ivar = "@#{name}"

        singleton_class.silence_redefinition_of_method("#{name}=")
        define_singleton_method("#{name}=") do |val|
          singleton_class.class_eval do
            redefine_method(name) { val }
          end

          if singleton_class?
            class_eval do
              redefine_method(name) do
                if instance_variable_defined? ivar
                  instance_variable_get ivar
                else
                  singleton_class.send name
                end
              end
            end
          end
          val
        end

        redefine_method(name) do
          if instance_variable_defined?(ivar)
            instance_variable_get ivar
          else
            self.class.public_send name
          end
        end

        redefine_method("#{name}?") { !!public_send(name) }

        redefine_method("#{name}=") do |val|
          instance_variable_set ivar, val
        end

        unless default_value.nil?
          self.send("#{name}=", default_value)
        end
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
stub_requests-0.1.3 lib/stub_requests/core_ext/class/attribute.rb
stub_requests-0.1.2 lib/stub_requests/core_ext/class/attribute.rb