Class: Miasma::Types::Model

Inherits:
Data
  • Object
show all
Includes:
Utils::ApiMethoding, Utils::Memoization
Defined in:
lib/miasma/types/model.rb

Overview

Base model

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Utils::ApiMethoding

#api_method_for

Methods inherited from Data

#from_json, #to_json

Constructor Details

#initialize(api, model_data = nil) ⇒ self

Build new model

Parameters:

  • api (Miasma::Types::Api)

    service API

  • model_data (Smash) (defaults to: nil)

    load model data if provided



35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/miasma/types/model.rb', line 35

def initialize(api, model_data = nil)
  @api = api
  @data = Smash.new
  @dirty = Smash.new
  if model_data
    if model_data.is_a?(Hash)
      load_data(model_data) unless model_data.empty?
    else
      raise TypeError.new "Expecting `model_data` to be of type `Hash`. Received: `#{model_data.class}`"
    end
  end
  self.custom = {}
end

Instance Attribute Details

#apiMiasma::Types::Api (readonly)

Returns underlying service API.

Returns:



14
15
16
# File 'lib/miasma/types/model.rb', line 14

def api
  @api
end

Class Method Details

.from_json(api, json) ⇒ Model

Build new model from JSON

Parameters:

Returns:



23
24
25
26
27
# File 'lib/miasma/types/model.rb', line 23

def from_json(api, json)
  instance = self.new(api)
  instance.from_json(json)
  instance
end

Instance Method Details

#destroyTrueClass, FalseClass

Destroy the model

Returns:

  • (TrueClass, FalseClass)

    destruction was performed



66
67
68
69
70
71
72
73
74
# File 'lib/miasma/types/model.rb', line 66

def destroy
  if persisted?
    perform_destroy
    reload
    true
  else
    false
  end
end

#id?String, Integer

Returns:

  • (String, Integer)


91
92
93
# File 'lib/miasma/types/model.rb', line 91

def id?
  data[:id] || dirty[:id]
end

#persisted?TrueClass, FalseClass

Returns model is persisted.

Returns:

  • (TrueClass, FalseClass)

    model is persisted



86
87
88
# File 'lib/miasma/types/model.rb', line 86

def persisted?
  id?
end

#reloadself

Reload the underlying data for model

Returns:

  • (self)


79
80
81
82
83
# File 'lib/miasma/types/model.rb', line 79

def reload
  clear_memoizations!
  perform_reload
  self
end

#saveTrueClass, FalseClass

Save changes to the model

Returns:

  • (TrueClass, FalseClass)

    save was performed



53
54
55
56
57
58
59
60
# File 'lib/miasma/types/model.rb', line 53

def save
  if dirty?
    perform_save
    reload
  else
    false
  end
end