Class: Lurch::Resource

Inherits:
Object
  • Object
show all
Defined in:
lib/lurch/resource.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(store, type, id) ⇒ Resource

Returns a new instance of Resource.



5
6
7
8
9
# File 'lib/lurch/resource.rb', line 5

def initialize(store, type, id)
  @store = store
  @type = Inflector.decode_type(type)
  @id = id
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *arguments, &block) ⇒ Object (private)



70
71
72
73
74
75
76
77
78
79
80
# File 'lib/lurch/resource.rb', line 70

def method_missing(method, *arguments, &block)
  raise Errors::ResourceNotLoaded, resource_class_name unless loaded?

  return resource_from_store.attribute(method) if resource_from_store.attribute?(method)
  if resource_from_store.relationship?(method)
    rel = resource_from_store.relationship(method)
    return rel.loaded? ? rel.data : rel
  end

  super
end

Instance Attribute Details

#idObject (readonly)

Returns the value of attribute id.



3
4
5
# File 'lib/lurch/resource.rb', line 3

def id
  @id
end

#typeObject (readonly)

Returns the value of attribute type.



3
4
5
# File 'lib/lurch/resource.rb', line 3

def type
  @type
end

Instance Method Details

#==(other) ⇒ Object



32
33
34
# File 'lib/lurch/resource.rb', line 32

def ==(other)
  eql?(other)
end

#[](attribute) ⇒ Object



40
41
42
43
44
# File 'lib/lurch/resource.rb', line 40

def [](attribute)
  raise Errors::ResourceNotLoaded, resource_class_name unless loaded?

  resource_from_store.attribute(attribute)
end

#attributesObject



20
21
22
23
24
# File 'lib/lurch/resource.rb', line 20

def attributes
  raise Errors::ResourceNotLoaded, resource_class_name unless loaded?

  resource_from_store.attributes
end

#eql?(other) ⇒ Boolean

Returns:

  • (Boolean)


36
37
38
# File 'lib/lurch/resource.rb', line 36

def eql?(other)
  id == other.id && type == other.type
end

#fetchObject



15
16
17
18
# File 'lib/lurch/resource.rb', line 15

def fetch
  @store.from(type).find(id)
  self
end

#inspectObject



50
51
52
53
54
55
56
57
# File 'lib/lurch/resource.rb', line 50

def inspect
  inspection = if loaded?
                 attributes.map { |name, value| "#{name}: #{value.inspect}" }.join(", ")
               else
                 "not loaded"
               end
  "#<#{self.class}[#{resource_class_name}] id: #{id.inspect}, #{inspection}>"
end

#loaded?Boolean

Returns:

  • (Boolean)


11
12
13
# File 'lib/lurch/resource.rb', line 11

def loaded?
  !!resource_from_store
end

#relationshipsObject



26
27
28
29
30
# File 'lib/lurch/resource.rb', line 26

def relationships
  raise Errors::ResourceNotLoaded, resource_class_name unless loaded?

  resource_from_store.relationships
end

#resource_class_nameObject



46
47
48
# File 'lib/lurch/resource.rb', line 46

def resource_class_name
  Inflector.classify(type)
end