Class: LetMeSendEmail::Models::Model

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/letmesendemail/models.rb

Overview

Application-friendly representation of an API response.

Nested hashes and arrays are recursively wrapped. Use #to_h for a defensive plain-data copy suitable for database persistence.

Instance Method Summary collapse

Constructor Details

#initialize(attributes) ⇒ Model

Returns a new instance of Model.

Parameters:

  • attributes (Hash)

    response attributes

Raises:

  • (ArgumentError)


16
17
18
19
20
21
22
# File 'lib/letmesendemail/models.rb', line 16

def initialize(attributes)
  raise ArgumentError, 'attributes must be a Hash' unless attributes.is_a?(Hash)

  @attributes = attributes.each_with_object({}) do |(key, value), result|
    result[key.to_s.dup.freeze] = Models.wrap(value)
  end.freeze
end

Instance Method Details

#[](key) ⇒ Object?

Returns wrapped field value.

Parameters:

  • key (String, Symbol)

    field name

Returns:

  • (Object, nil)

    wrapped field value



26
27
28
# File 'lib/letmesendemail/models.rb', line 26

def [](key)
  @attributes[key.to_s]
end

#as_jsonHash

Rails-compatible JSON representation.

Returns:

  • (Hash)


59
60
61
# File 'lib/letmesendemail/models.rb', line 59

def as_json(*)
  to_h
end

#each {|key, value| ... } ⇒ Enumerator, self

Iterates through response fields.

Yield Parameters:

  • key (String)
  • value (Object)

Returns:

  • (Enumerator, self)


46
47
48
49
50
# File 'lib/letmesendemail/models.rb', line 46

def each(&block)
  return enum_for(:each) unless block

  @attributes.each(&block)
end

#fetch(key, *defaults) ⇒ Object

Returns wrapped field value.

Parameters:

  • key (String, Symbol)

    field name

Returns:

  • (Object)

    wrapped field value



32
33
34
# File 'lib/letmesendemail/models.rb', line 32

def fetch(key, *defaults, &)
  @attributes.fetch(key.to_s, *defaults, &)
end

#inspectString

Returns:

  • (String)


69
70
71
# File 'lib/letmesendemail/models.rb', line 69

def inspect
  "#<#{self.class.name} #{@attributes.inspect}>"
end

#key?(key) ⇒ Boolean

Returns whether the field exists.

Parameters:

  • key (String, Symbol)

    field name

Returns:

  • (Boolean)

    whether the field exists



38
39
40
# File 'lib/letmesendemail/models.rb', line 38

def key?(key)
  @attributes.key?(key.to_s)
end

#to_hHash

Returns recursive defensive plain-data copy.

Returns:

  • (Hash)

    recursive defensive plain-data copy



53
54
55
# File 'lib/letmesendemail/models.rb', line 53

def to_h
  Models.unwrap(@attributes)
end

#to_json(*args) ⇒ String

Returns JSON document.

Returns:

  • (String)

    JSON document



64
65
66
# File 'lib/letmesendemail/models.rb', line 64

def to_json(*args)
  to_h.to_json(*args)
end