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.4.0.colin.7 lib/declare_schema/extensions/module.rb
declare_schema-1.4.0.colin.6 lib/declare_schema/extensions/module.rb
declare_schema-1.4.0.colin.5 lib/declare_schema/extensions/module.rb
declare_schema-1.4.0.colin.4 lib/declare_schema/extensions/module.rb
declare_schema-1.4.0.colin.3 lib/declare_schema/extensions/module.rb
declare_schema-1.4.0.colin.2 lib/declare_schema/extensions/module.rb
declare_schema-1.4.0.colin.1 lib/declare_schema/extensions/module.rb
declare_schema-1.3.2 lib/declare_schema/extensions/module.rb
declare_schema-1.3.2.rp.1 lib/declare_schema/extensions/module.rb
declare_schema-1.3.1 lib/declare_schema/extensions/module.rb
declare_schema-1.3.1.colin.1 lib/declare_schema/extensions/module.rb
declare_schema-1.3.0 lib/declare_schema/extensions/module.rb
declare_schema-1.3.0.colin.1 lib/declare_schema/extensions/module.rb
declare_schema-1.2.3 lib/declare_schema/extensions/module.rb
declare_schema-1.2.3.pre.ga.11 lib/declare_schema/extensions/module.rb
declare_schema-1.2.3.pre.ga.10 lib/declare_schema/extensions/module.rb
declare_schema-1.2.3.pre.ga.9 lib/declare_schema/extensions/module.rb
declare_schema-1.2.3.pre.ga.8 lib/declare_schema/extensions/module.rb
declare_schema-1.2.3.pre.ga.7 lib/declare_schema/extensions/module.rb
declare_schema-1.2.3.pre.ga.6 lib/declare_schema/extensions/module.rb