Module: Dry::Core::ClassAttributes

Includes:
Constants
Defined in:
lib/dry/core/class_attributes.rb

Overview

Internal support module for class-level settings

Constant Summary

Constants included from Constants

Dry::Core::Constants::EMPTY_ARRAY, Dry::Core::Constants::EMPTY_HASH, Dry::Core::Constants::EMPTY_OPTS, Dry::Core::Constants::EMPTY_SET, Dry::Core::Constants::EMPTY_STRING, Dry::Core::Constants::Undefined

Instance Method Summary collapse

Methods included from Constants

included

Instance Method Details

#defines(*args) ⇒ Object

Specify what attirubtes a class will use

Examples:

class MyClass
  extend Dry::Core::ClassAttributes

  defines :one, :two

  one 1
  two 2
end

class OtherClass < MyClass
  two 'two'
end

MyClass.one # => 1
MyClass.two # => 2

OtherClass.one # => 1
OtherClass.two # => 'two'


32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/dry/core/class_attributes.rb', line 32

def defines(*args)
  mod = Module.new do
    args.each do |name|
      define_method(name) do |value = Undefined|
        ivar = "@#{name}"

        if value == Undefined
          if instance_variable_defined?(ivar)
            instance_variable_get(ivar)
          else
            nil
          end
        else
          instance_variable_set(ivar, value)
        end
      end
    end

    define_method(:inherited) do |klass|
      args.each { |name| klass.public_send(name, send(name)) }

      super(klass)
    end
  end

  extend(mod)
end