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



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

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:



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

def api
  @api
end

Class Method Details

.from_json(api, json) ⇒ Model

Build new model from JSON

Parameters:

Returns:



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

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



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

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

#id?String, Integer

Returns:

  • (String, Integer)


93
94
95
# File 'lib/miasma/types/model.rb', line 93

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

#persisted?TrueClass, FalseClass

Returns model is persisted.

Returns:

  • (TrueClass, FalseClass)

    model is persisted



88
89
90
# File 'lib/miasma/types/model.rb', line 88

def persisted?
  id?
end

#reloadself

Reload the underlying data for model

Returns:

  • (self)


81
82
83
84
85
# File 'lib/miasma/types/model.rb', line 81

def reload
  clear_memoizations!
  perform_reload
  self
end

#saveTrueClass, FalseClass

Save changes to the model

Returns:

  • (TrueClass, FalseClass)

    save was performed



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

def save
  if(dirty?)
    perform_save
    reload
  else
    false
  end
end