Class: LazyLazer::InternalModel

Inherits:
Object
  • Object
show all
Defined in:
lib/lazy_lazer/internal_model.rb

Overview

A delegator for internal operations.

Instance Method Summary collapse

Constructor Details

#initialize(key_metadata, parent) ⇒ InternalModel

Create an internal model with a reference to a public model.

Parameters:

  • key_metadata (Hash<Symbol, KeyMetadata>)

    a reference to a property hash

  • parent (LazyLazer)

    a reference to a LazyLazer model



9
10
11
12
13
14
# File 'lib/lazy_lazer/internal_model.rb', line 9

def initialize(, parent)
  @key_metadata = 
  @parent = parent
  @source_hash = {}
  @cache_hash = {}
end

Instance Method Details

#fetch(key_name) ⇒ Object

Get the value of a key (fetching it from the cache if possible)

Parameters:

  • key_name (Symbol)

    the name of the key

Returns:

  • (Object)

    the returned value

Raises:

  • MissingAttribute if the attribute wasn't found and there isn't a default



37
38
39
40
# File 'lib/lazy_lazer/internal_model.rb', line 37

def fetch(key_name)
  @cache_hash[key_name] ||= load_key_from_source(key_name)
  @cache_hash[key_name]
end

#merge!(attributes) ⇒ nil

Merge a hash into the model.

Parameters:

  • attributes (Hash<Symbol, Object>)

    the attributes to merge

Returns:

  • (nil)


45
46
47
48
49
# File 'lib/lazy_lazer/internal_model.rb', line 45

def merge!(attributes)
  @cache_hash.clear
  @source_hash.merge!(attributes)
  nil
end

#to_hHash

Converts all unconverted keys and packages them as a hash.

Returns:

  • (Hash)

    the converted hash



28
29
30
31
# File 'lib/lazy_lazer/internal_model.rb', line 28

def to_h
  todo = @key_metadata.keys - @cache_hash.keys
  todo.each_with_object(@cache_hash) { |key, cache| cache[key] = load_key_from_source(key) }.dup
end

#verify_required!void

This method returns an undefined value.

Verify that all the keys marked as required are present.

Raises:

  • RequiredAttribute if a required attribute is missing



19
20
21
22
23
24
# File 'lib/lazy_lazer/internal_model.rb', line 19

def verify_required!
  @key_metadata.each do |key_name, meta|
    next if !meta.required? || @source_hash.key?(meta.source_key)
    raise RequiredAttribute, "#{@parent} requires `#{key_name}`"
  end
end