Class: Miasma::Types::Model

Inherits:
Data
  • Object
show all
Includes:
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::Memoization

#_memo, #clear_memoizations!, #memoize, #unmemoize

Methods inherited from Data

#from_json, #to_json

Methods included from Utils::Lazy

included

Constructor Details

#initialize(api, model_data = nil) ⇒ self

Build new model

Parameters:



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

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
end

Instance Attribute Details

#apiMiasma::Types::Api (readonly)

Returns underlying service API.

Returns:



12
13
14
# File 'lib/miasma/types/model.rb', line 12

def api
  @api
end

Class Method Details

.from_json(api, json) ⇒ Model

Build new model from JSON

Parameters:

Returns:



21
22
23
24
25
# File 'lib/miasma/types/model.rb', line 21

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



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

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

#id?String, Integer

Returns:

  • (String, Integer)


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

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

#persisted?TrueClass, FalseClass

Returns model is persisted.

Returns:

  • (TrueClass, FalseClass)

    model is persisted



84
85
86
# File 'lib/miasma/types/model.rb', line 84

def persisted?
  id?
end

#reloadself

Reload the underlying data for model

Returns:

  • (self)


77
78
79
80
81
# File 'lib/miasma/types/model.rb', line 77

def reload
  clear_memoizations!
  perform_reload
  self
end

#saveTrueClass, FalseClass

Save changes to the model

Returns:

  • (TrueClass, FalseClass)

    save was performed



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

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