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, type: Object) ⇒ Object

Specify what attributes a class will use

Examples:

class ExtraClass
  extend Dry::Core::ClassAttributes

  defines :hello

  hello 'world'
end

with inheritance and type checking


class MyClass
  extend Dry::Core::ClassAttributes

  defines :one, :two, type: Integer

  one 1
  two 2
end

class OtherClass < MyClass
  two 3
end

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

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

with dry-types


class Foo
  extend Dry::Core::ClassAttributes

  defines :one, :two, type: Dry::Types['strict.int']
end


52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/dry/core/class_attributes.rb', line 52

def defines(*args, type: Object)
  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
          raise InvalidClassAttributeValue.new(name, value) unless type === value

          instance_variable_set(ivar, value)
        end
      end
    end

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

      super(klass)
    end
  end

  extend(mod)
end