Class: ContractedValue::Value

Inherits:
Object
  • Object
show all
Defined in:
lib/contracted_value/core.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(input_attr_values = {}) ⇒ Value

rubocop:disable Metrics/CyclomaticComplexity rubocop:disable Metrics/AbcSize



226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
# File 'lib/contracted_value/core.rb', line 226

def initialize(input_attr_values = {})
  input_attr_values_hash =
    case input_attr_values
    when ::Hash
      input_attr_values
    when Value
      input_attr_values.to_h
    else
      raise(
        Errors::InvalidInputType.new(
          input_attr_values,
        ),
      )
    end

  self.class.send(:attribute_set).each_attribute do |attribute|
    attr_value = attribute.extract_value(input_attr_values_hash)

    sometimes_frozen_attr_value =
      case attribute.refrigeration_mode
      when RefrigerationMode::Enum::DEEP
        # Use ice_nine for deep freezing
        ::IceNine.deep_freeze(attr_value)
      when RefrigerationMode::Enum::SHALLOW
        # No need to re-freeze
        attr_value.frozen? ? attr_value : attr_value.freeze
      when RefrigerationMode::Enum::NONE
        # No freezing
        attr_value
      else
        raise Errors::InvalidRefrigerationMode.new(
          refrigeration_mode,
        )
      end

    # Using symbol since attribute names are limited in number
    # An alternative would be using frozen string
    instance_variable_set(
      :"@#{attribute.name}",
      sometimes_frozen_attr_value,
    )
  end

  freeze
end

Class Method Details

.inherited(klass) ⇒ Object



283
284
285
286
287
# File 'lib/contracted_value/core.rb', line 283

def inherited(klass)
  super

  klass.instance_variable_set(:@attribute_set, AttributeSet.new)
end

Instance Method Details

#to_hObject

rubocop:enable Metrics/AbcSize rubocop:enable Metrics/CyclomaticComplexity



274
275
276
277
278
279
# File 'lib/contracted_value/core.rb', line 274

def to_h
  self.class.send(:attribute_set).
    each_attribute.each_with_object({}) do |attribute, hash|
      hash[attribute.name] = instance_variable_get(:"@#{attribute.name}")
    end
end