Module: NeverBounce::API::Feature::Igetset::InstanceMethods

Defined in:
lib/never_bounce/api/feature/igetset.rb

Instance Method Summary collapse

Instance Method Details

#igetset(name, &compute) ⇒ Object (private)

Get/set an OTF instance variable of any type.

Ruby’s ||= works nicely with object instances, but requires special bulky treatment for nil and false. For example, this will cause a hidden glitch since == can evaluate to false:

@is_verbose ||= begin
  # This clause will be evaluated *every time* if its value is `false`.
  ENV["VERBOSE"] == "y"
end

There’s a number of solutions to this problem, all of which involve calling instance_variable_* a few times per attribute accessor.

igetset does this job for you. All you have to do is specify a block to compute the value.

igetset(:is_verbose) { ENV["VERBOSE"] == "y" }

See source for details.



32
33
34
35
36
37
38
# File 'lib/never_bounce/api/feature/igetset.rb', line 32

def igetset(name, &compute)
  if instance_variable_defined?(k = "@#{name}")
    instance_variable_get(k)
  else
    instance_variable_set(k, compute.call)
  end
end