Module: AttrMagic::InstanceMethods

Defined in:
lib/attr_magic/instance_methods.rb

Instance Method Summary collapse

Instance Method Details

#igetset(name, &compute) ⇒ mixed

Memoize a lazy attribute, given its computation block.

def full_name
  igetset(__method__) { [first_name, last_name].compact.join(" ").strip }
end

Parameters:

  • name (Symbol | String)

Returns:

  • (mixed)

    The result of compute.

See Also:



14
15
16
17
18
19
20
21
# File 'lib/attr_magic/instance_methods.rb', line 14

def igetset(name, &compute)
  if instance_variable_defined?(k = "@#{name}")
    instance_variable_get(k)
  else
    raise ArgumentError, "Code block must be given" unless compute
    instance_variable_set(k, compute.call)
  end
end

#igetwrite(name, &compute) ⇒ mixed

Same as #igetset, but this one calls an attribute writer to store the computed value into the object.

Parameters:

  • name (Symbol | String)

Returns:

  • (mixed)

    The result of compute.

See Also:



28
29
30
31
32
33
34
35
# File 'lib/attr_magic/instance_methods.rb', line 28

def igetwrite(name, &compute)
  if instance_variable_defined?(k = "@#{name}")
    instance_variable_get(k)
  else
    raise ArgumentError, "Code block must be given" unless compute
    send("#{name}=", compute.call)
  end
end

#require_attr(name, predicate = :not_nil?) ⇒ mixed

Require an attribute to be set, present, valid or not invalid.

require_attr(:name)                 # Require not to be `.nil?`.
require_attr(:obj, :valid)          # Require to be `.valid`.
require_attr(:items, :present?)     # Require to be `.present?`.
require_attr(:items, :not_empty?)   # Require not to be `.empty?`.

Parameters:

  • name (Symbol | String)
  • predicate (Symbol | String) (defaults to: :not_nil?)

Returns:

  • (mixed)

    Attribute value.

Raises:

  • (RuntimeError)


48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/attr_magic/instance_methods.rb', line 48

def require_attr(name, predicate = :not_nil?)
  # Declare in the scope.
  m = nil

  # `check` is a function returning `true` if the value is good.
  m, verb, check = if ((sp = predicate.to_s).start_with? "not_")
    [
      sp[4..-1],
      "must not",
      -> (v) { !v.public_send(m) },
    ]
  else
    [
      sp,
      "must",
      -> (v) { v.public_send(m) },
    ]
  end

  raise ArgumentError, "Invalid predicate: #{predicate.inspect}" if m.empty?

  # NOTE: Shorten the error backtrace to the minimum.

  # Get and check the value.
  v = send(name)
  check.(v) or raise "Attribute `#{name}` #{verb} be #{m.chomp('?')}: #{v.inspect}"

  v
end