Sha256: 78e1ced3260fecfed2e043e8f3b1f95e879db37542667818b2e5fc2d4e8e265a

Contents?: true

Size: 1.85 KB

Versions: 6

Compression:

Stored size: 1.85 KB

Contents

require 'dry/core/constants'
require 'dry/core/errors'

module Dry
  module Core
    # Internal support module for class-level settings
    #
    # @api public
    module ClassAttributes
      include Constants

      # Specify what attributes a class will use
      #
      # @example
      #  class ExtraClass
      #    extend Dry::Core::ClassAttributes
      #
      #    defines :hello
      #
      #    hello 'world'
      #  end
      #
      # @example 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
      #
      # @example with dry-types
      #
      #  class Foo
      #    extend Dry::Core::ClassAttributes
      #
      #    defines :one, :two, type: Dry::Types['strict.int']
      #  end
      #
      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
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
dry-core-0.4.7 lib/dry/core/class_attributes.rb
dry-core-0.4.6 lib/dry/core/class_attributes.rb
dry-core-0.4.5 lib/dry/core/class_attributes.rb
dry-core-0.4.4 lib/dry/core/class_attributes.rb
dry-core-0.4.3 lib/dry/core/class_attributes.rb
dry-core-0.4.2 lib/dry/core/class_attributes.rb