Module: ParamsReady::Extensions::LateInit

Included in:
Parameter::AbstractDefinition, Value::GenericCoder
Defined in:
lib/params_ready/extensions/late_init.rb

Instance Method Summary collapse

Instance Method Details

#late_init(name, obligatory: true, freeze: true, getter: true, boolean: false, once: true, definite: true, &block) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/params_ready/extensions/late_init.rb', line 6

def late_init(
  name,
  obligatory: true,
  freeze: true,
  getter: true,
  boolean: false,
  once: true,
  definite: true,
  &block
)
  ivar = :"@#{name}"
  define_method "set_#{name}" do |value|
    raise ParamsReadyError, "Can't initialize '#{name}' to nil" if value.nil? && definite
    value = instance_exec(value, &block) unless block.nil?
    next if value == Extensions::Undefined

    current = instance_variable_get ivar
    raise ParamsReadyError, "Variable '#{name}' already set" unless current.nil? || !once
    value.freeze if freeze
    instance_variable_set "@#{name}", value
  end

  if boolean
    define_method "#{name}?" do
      instance_variable_get ivar
    end
  end
  attr_reader name if getter
  obligatory! name if obligatory
end