Module: AttributesDSL

Defined in:
lib/attributes_dsl.rb,
lib/attributes_dsl/attribute.rb,
lib/attributes_dsl/attributes.rb

Overview

Simple DSL for PORO attributes

Author:

Defined Under Namespace

Modules: InstanceMethods Classes: Attribute, Attributes

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.extended(klass) ⇒ Object



72
73
74
75
# File 'lib/attributes_dsl.rb', line 72

def self.extended(klass)
  # use __send__ for compatibility to 1.9.3 (where `.include` was private)
  klass.__send__(:include, InstanceMethods)
end

Instance Method Details

#attribute(name, options = {}, &coercer) ⇒ undefined

Retisters an attribute by name, options and coercer

Examples:

class MyClass
  extend AttributeDSL

  attribute :foo, required: true do |value|
    value.to_i % 5
  end

  attribute :bar, default: :BAR
end

Parameters:

  • name (#to_sym)

    The unique name of the attribute

  • coercer (Proc)

    The proc to coerce values (including the default ones)

  • options (Hash) (defaults to: {})

Options Hash (options):

  • :required (Boolean)

    Whether the attribute should be required by the initializer This option is ignored (set to false) when default value is provided

  • :default (Object)

    The default value for the attribute

Returns:

  • (undefined)


52
53
54
55
56
57
# File 'lib/attributes_dsl.rb', line 52

def attribute(name, options = {}, &coercer)
  s_name = name.to_sym
  @attributes = attributes.register(s_name, options, &coercer)

  define_method(s_name) { attributes.fetch(s_name) }
end

#attributesAttributeDSL::Attributes

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

The mutable collection of declared attributes

Returns:

  • (AttributeDSL::Attributes)


23
24
25
# File 'lib/attributes_dsl.rb', line 23

def attributes
  @attributes ||= Attributes.new
end

#new(hash) ⇒ Object

Object contstructor that filters hash of attributes

Parameters:

  • hash (Hash)

    The hash of attributes to be assinged

Returns:

  • (Object)

Raises:

  • (ArgumentError)

    in case a required attribute is missed



67
68
69
# File 'lib/attributes_dsl.rb', line 67

def new(hash)
  super attributes.extract(hash)
end