Module: AttrCoerced

Defined in:
lib/attr_coerced.rb

Overview

Namespace for the code of the ‘attr_coerced’ gem

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



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

def attr_coerced(name, type, default: nil)
  [
    attr_coerced_reader(name, type, default: default),
    attr_coerced_writer(name, type)
  ]
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



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

def attr_coerced_reader(name, type, default: nil)
  define_method(name) { type.new(instance_eval("@#{ name }") || default) }

  name.to_sym
end

#attr_coerced_writer(name, type) ⇒ Symbol

Defines value setter for a coercible attribute

Examples:

attr_coerced_writer :name, Name

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



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

def attr_coerced_writer(name, type)
  define_method "#{ name }=" do |value|
    instance_eval "@#{ name } = #{ type }.new(value)"
  end

  "#{ name }=".to_sym
end