Module: AttrCoerced

Defined in:
lib/attr_coerced.rb,
lib/attr_coerced/coercer.rb

Overview

Namespace for the code of the ‘attr_coerced’ gem

Defined Under Namespace

Classes: Coercer

Instance Method Summary collapse

Instance Method Details

#attr_coerced(name, type, default: nil) ⇒ Symbol

Defines both value getter and setter for a coercible attribute

Examples:

attr_coerced :name, Name, default: "foo"

Parameters:

  • name (#to_sym)

    The name of the attribute

  • type (Class)

    The type of the attribute

  • [Object] (Hash)

    a customizable set of options

Returns:

  • (Symbol)

    name of the attribute



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

def attr_coerced(*args)
  [attr_coerced_reader(*args), attr_coerced_writer(*args)]
end

#attr_coerced_reader(name, type, default: nil) ⇒ Symbol

Defines value getter for a coercible attribute

Examples:

attr_coerced_reader :name, Name, default: "foo"

Parameters:

  • name (#to_sym)

    The name of the attribute

  • type (Class)

    The type of the attribute

  • [Object] (Hash)

    a customizable set of options

Returns:

  • (Symbol)

    name of the attribute



36
37
38
39
40
41
42
43
# File 'lib/attr_coerced.rb', line 36

def attr_coerced_reader(name, type, default: nil)
  define_method name do
    value = instance_variable_get "@#{ name }"
    Coercer.get value, default, type
  end

  name.to_sym
end

#attr_coerced_writer(name, type, default: nil) ⇒ Symbol

Defines value setter for a coercible attribute

Examples:

attr_coerced_writer :name, Name, default: "foo"

Parameters:

  • name (#to_sym)

    The name of the attribute

  • type (Class)

    The type of the attribute

  • [Object] (Hash)

    a customizable set of options

Returns:

  • (Symbol)

    name of the attribute



54
55
56
57
58
59
60
61
# File 'lib/attr_coerced.rb', line 54

def attr_coerced_writer(name, type, default: nil)
  define_method "#{ name }=" do |value|
    new_value = Coercer.get value, default, type
    instance_variable_set "@#{ name }", new_value
  end

  :"#{ name }="
end