Class: ViewModel::Reference

Inherits:
Object
  • Object
show all
Defined in:
lib/view_model/reference.rb

Overview

Key to identify a viewmodel with some kind of inherent ID (e.g. an ViewModel::ActiveRecord)

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(viewmodel_class, model_id) ⇒ Reference

Returns a new instance of Reference.



8
9
10
11
# File 'lib/view_model/reference.rb', line 8

def initialize(viewmodel_class, model_id)
  @viewmodel_class = viewmodel_class
  @model_id        = model_id
end

Instance Attribute Details

#model_idObject

Returns the value of attribute model_id.



6
7
8
# File 'lib/view_model/reference.rb', line 6

def model_id
  @model_id
end

#viewmodel_classObject

Returns the value of attribute viewmodel_class.



6
7
8
# File 'lib/view_model/reference.rb', line 6

def viewmodel_class
  @viewmodel_class
end

Instance Method Details

#==(other) ⇒ Object Also known as: eql?



21
22
23
24
25
# File 'lib/view_model/reference.rb', line 21

def ==(other)
  other.class             == self.class &&
    other.viewmodel_class == viewmodel_class &&
    other.model_id        == model_id
end

#hashObject



29
30
31
# File 'lib/view_model/reference.rb', line 29

def hash
  [viewmodel_class, model_id].hash
end

#inspectObject



17
18
19
# File 'lib/view_model/reference.rb', line 17

def inspect
  "<Ref:#{self}>"
end

#stable_referenceObject

Generate a stable reference key for this viewmodel using type name and id

Raises:

  • (RuntimeError)


34
35
36
37
38
39
# File 'lib/view_model/reference.rb', line 34

def stable_reference
  raise RuntimeError.new('Model id required to generate a stable reference') unless model_id

  hash = Digest::SHA256.base64digest("#{viewmodel_class.name}.#{model_id}")
  "ref:h:#{hash}"
end

#to_sObject



13
14
15
# File 'lib/view_model/reference.rb', line 13

def to_s
  "'#{viewmodel_class.view_name}(id=#{model_id})'"
end