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-0.13.0 lib/declare_schema/extensions/module.rb
declare_schema-0.13.0.pre.2 lib/declare_schema/extensions/module.rb
declare_schema-0.13.0.pre.1 lib/declare_schema/extensions/module.rb
declare_schema-0.12.1 lib/declare_schema/extensions/module.rb
declare_schema-0.12.0 lib/declare_schema/extensions/module.rb
declare_schema-0.12.0.pre.2 lib/declare_schema/extensions/module.rb
declare_schema-0.12.0.pre.1 lib/declare_schema/extensions/module.rb
declare_schema-0.11.1 lib/declare_schema/extensions/module.rb
declare_schema-0.11.0 lib/declare_schema/extensions/module.rb
declare_schema-0.10.1 lib/declare_schema/extensions/module.rb
declare_schema-0.10.0 lib/declare_schema/extensions/module.rb
declare_schema-0.10.0.pre.dc.1 lib/declare_schema/extensions/module.rb
declare_schema-0.9.0 lib/declare_schema/extensions/module.rb
declare_schema-0.8.0 lib/declare_schema/extensions/module.rb
declare_schema-0.8.0.pre.6 lib/declare_schema/extensions/module.rb
declare_schema-0.8.0.pre.5 lib/declare_schema/extensions/module.rb
declare_schema-0.8.0.pre.4 lib/declare_schema/extensions/module.rb
declare_schema-0.8.0.pre.3 lib/declare_schema/extensions/module.rb
declare_schema-0.8.0.pre.2 lib/declare_schema/extensions/module.rb
declare_schema-0.8.0.pre.1 lib/declare_schema/extensions/module.rb