Class: Toast::Association

Inherits:
Resource show all
Defined in:
lib/toast/association.rb

Instance Attribute Summary collapse

Attributes inherited from Resource

#media_type

Instance Method Summary collapse

Methods inherited from Resource

#apply, build, get_class_by_resource_name

Constructor Details

#initialize(model, id, subresource_name, format) ⇒ Association

Returns a new instance of Association.



6
7
8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/toast/association.rb', line 6

def initialize model, id, subresource_name, format
  unless model.toast_config.exposed_associations.include? subresource_name
    raise ResourceNotFound
  end

  @model = model
  @record = model.find(id) rescue raise(ResourceNotFound)
  @collection = subresource_name
  @format = format

  @associate_model = Resource.get_class_by_resource_name subresource_name
  @associate_model.uri_base = @model.uri_base
  
end

Instance Attribute Details

#modelObject (readonly)

Returns the value of attribute model.



4
5
6
# File 'lib/toast/association.rb', line 4

def model
  @model
end

Instance Method Details

#deleteObject

Raises:



65
66
67
# File 'lib/toast/association.rb', line 65

def delete
  raise MethodNotAllowed
end

#getObject



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/toast/association.rb', line 21

def get
  result = @record.send(@collection)

  if result.is_a? Array 
    {
      :json => result.map{|r| r.exposed_attributes(:in_collection => true)},
      :status => :ok
    }
  else
    {
      :json => result.exposed_attributes(:in_collection => true),
      :status => :ok
    }
  end

end

#post(payload) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/toast/association.rb', line 42

def post payload

  if self.media_type != @associate_model.toast_config.media_type
    raise UnsupportedMediaType
  end

  if payload.keys.to_set != (@associate_model.toast_config.exposed_attributes.to_set - @associate_model.toast_config.auto_fields.to_set)
    raise PayloadInvalid
  end

  unless payload.is_a? Hash
    raise PayloadFormatError
  end 

  record = @record.send(@collection).create payload
  
  {
    :json => record.exposed_attributes,
    :location => record.uri,
    :status => :created
  }
end

#putObject

Raises:



38
39
40
# File 'lib/toast/association.rb', line 38

def put
  raise MethodNotAllowed
end