Module: Strict::Attributes::Instance

Defined in:
lib/strict/attributes/instance.rb

Instance Method Summary collapse

Instance Method Details

#initialize(**attributes) ⇒ Object

rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/MethodLength, Metrics/PerceivedComplexity



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
36
37
38
39
40
# File 'lib/strict/attributes/instance.rb', line 7

def initialize(**attributes)
  remaining_attributes = Set.new(attributes.keys)
  invalid_attributes = nil
  missing_attributes = nil

  self.class.strict_attributes.each do |attribute|
    if remaining_attributes.delete?(attribute.name)
      value = attributes.fetch(attribute.name)
    elsif attribute.optional?
      value = attribute.default_generator.call
    else
      missing_attributes ||= []
      missing_attributes << attribute.name
      next
    end

    value = attribute.coerce(value, for_class: self.class)
    if attribute.valid?(value)
      instance_variable_set(attribute.instance_variable, value)
    else
      invalid_attributes ||= {}
      invalid_attributes[attribute] = value
    end
  end

  return if remaining_attributes.none? && invalid_attributes.nil? && missing_attributes.nil?

  raise InitializationError.new(
    initializable_class: self.class,
    remaining_attributes: remaining_attributes,
    invalid_attributes: invalid_attributes,
    missing_attributes: missing_attributes
  )
end

#inspectObject



49
50
51
52
53
54
55
# File 'lib/strict/attributes/instance.rb', line 49

def inspect
  if self.class.strict_attributes.any?
    "#<#{self.class} #{to_h.map { |key, value| "#{key}=#{value.inspect}" }.join(' ')}>"
  else
    "#<#{self.class}>"
  end
end

#pretty_print(pp) ⇒ Object



57
58
59
60
61
62
63
64
65
# File 'lib/strict/attributes/instance.rb', line 57

def pretty_print(pp)
  pp.object_group(self) do
    to_h.each do |key, value|
      pp.breakable
      pp.text("#{key}=")
      pp.pp(value)
    end
  end
end

#to_hObject

rubocop:enable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/MethodLength, Metrics/PerceivedComplexity



43
44
45
46
47
# File 'lib/strict/attributes/instance.rb', line 43

def to_h
  self.class.strict_attributes.to_h do |attribute|
    [attribute.name, public_send(attribute.name)]
  end
end