Module: AttributesDSL

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

Overview

Simple DSL for PORO attributes

Defined Under Namespace

Modules: InstanceMethods Classes: Attribute, Attributes

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.extended(klass) ⇒ Object



60
61
62
63
# File 'lib/attributes_dsl.rb', line 60

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

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



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



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

def attributes
  @attributes ||= Attributes.new
end

#inherited(klass) ⇒ Object



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

def inherited(klass)
  klass.instance_variable_set(:@attributes, attributes)
end