Sha256: d0f74c1c56c9f08b9fc4500c976a803a826654174032663d298269cd27e6db0a

Contents?: true

Size: 1000 Bytes

Versions: 104

Compression:

Stored size: 1000 Bytes

Contents

# frozen_string_literal: true

class Module

  private

  # Creates a class attribute reader that will delegate to the superclass
  # if not defined on self. Default values can be a Proc object that takes the class as a parameter.
  def inheriting_cattr_reader(*names)
    receiver =
      if self.class == Module
        self
      else
        singleton_class
      end

    names_with_defaults = (names.pop if names.last.is_a?(Hash)) || {}

    (names + names_with_defaults.keys).each do |name|
      ivar_name = "@#{name}"
      block = names_with_defaults[name]

      receiver.send(:define_method, name) do
        if instance_variable_defined? ivar_name
          instance_variable_get(ivar_name)
        else
          superclass.respond_to?(name) && superclass.send(name) ||
            block && begin
              result = block.is_a?(Proc) ? block.call(self) : block
              instance_variable_set(ivar_name, result) if result
            end
        end
      end
    end
  end
end

Version data entries

104 entries across 104 versions & 1 rubygems

Version Path
declare_schema-1.2.3.pre.ga.5 lib/declare_schema/extensions/module.rb
declare_schema-1.2.3.pre.ga.4 lib/declare_schema/extensions/module.rb
declare_schema-1.2.3.pre.ga.2 lib/declare_schema/extensions/module.rb
declare_schema-1.2.3.pre.ga.1 lib/declare_schema/extensions/module.rb
declare_schema-1.2.3.pre.ga.0 lib/declare_schema/extensions/module.rb
declare_schema-1.2.2 lib/declare_schema/extensions/module.rb
declare_schema-1.2.2.pre.0 lib/declare_schema/extensions/module.rb
declare_schema-1.2.1 lib/declare_schema/extensions/module.rb
declare_schema-1.2.0 lib/declare_schema/extensions/module.rb
declare_schema-1.2.0.pre.1 lib/declare_schema/extensions/module.rb
declare_schema-1.1.0 lib/declare_schema/extensions/module.rb
declare_schema-1.0.2 lib/declare_schema/extensions/module.rb
declare_schema-1.0.1 lib/declare_schema/extensions/module.rb
declare_schema-1.0.0 lib/declare_schema/extensions/module.rb
declare_schema-0.14.3 lib/declare_schema/extensions/module.rb
declare_schema-0.14.2 lib/declare_schema/extensions/module.rb
declare_schema-0.14.1 lib/declare_schema/extensions/module.rb
declare_schema-0.14.0 lib/declare_schema/extensions/module.rb
declare_schema-0.13.2 lib/declare_schema/extensions/module.rb
declare_schema-0.13.1 lib/declare_schema/extensions/module.rb