Class: Toast::Record

Inherits:
Resource show all
Defined in:
lib/toast/record.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, format) ⇒ Record

Returns a new instance of Record.



6
7
8
9
10
# File 'lib/toast/record.rb', line 6

def initialize model, id, format
  @model = model      
  @record = model.find(id) rescue raise(ResourceNotFound.new)
  @format = format
end

Instance Attribute Details

#modelObject (readonly)

Returns the value of attribute model.



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

def model
  @model
end

Instance Method Details

#deleteObject



57
58
59
60
61
62
63
# File 'lib/toast/record.rb', line 57

def delete
  @record.destroy
  {
    :nothing => true,
    :status => :ok
  }
end

#getObject



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/toast/record.rb', line 40

def get
  case @format
  when "html", "xml"
    {
      :template => "resources/#{model.to_s.underscore}",
      :locals => { model.to_s.underscore.to_sym => @record } # full record, view should filter
    }
  when "json"
    {
      :json => @record.exposed_attributes,
      :status => :ok
    }
  else 
    raise ResourceNotFound
  end
end

#post(payload) ⇒ Object

Raises:



12
13
14
# File 'lib/toast/record.rb', line 12

def post payload
  raise MethodNotAllowed
end

#put(payload) ⇒ Object

get, put, delete, post return a Hash that can be used as argument for ActionController#render



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

def put payload       
  if self.media_type != @model.toast_config.media_type
    raise UnsupportedMediaType
  end

  unless payload.is_a? Hash
    raise PayloadFormatError
  end

  if payload.keys.to_set != (@model.toast_config.exposed_attributes.to_set - @model.toast_config.auto_fields.to_set)
    raise PayloadInvalid
  end
  
  @record.update_attributes payload
  { 
    :json => @record.exposed_attributes,
    :status => :ok,
    :location => @record.uri
  }
end