Module: Restfulie::Server::Controller

Defined in:
lib/restfulie/server/controller.rb

Overview

Controller which adds default CRUD + search + other operations. TODO: move these actions to controller/base.rb (maybe using InheritedResources, maybe not)

Instance Method Summary (collapse)

Instance Method Details

- (Object) create

creates a model based on the request media-type extracted from its content-type



7
8
9
10
11
12
13
14
15
16
17
# File 'lib/restfulie/server/controller.rb', line 7

def create
  type = model_type
  return head 415 unless fits_content(type, request.headers['CONTENT_TYPE'])

  @model = type.from_xml request.body.string
  if @model.save
    render_created @model
  else
    render :xml => @model.errors, :status => :unprocessable_entity
  end
end

- (Object) destroy

destroys this resource



31
32
33
34
35
# File 'lib/restfulie/server/controller.rb', line 31

def destroy
  @model = model_type.find(params[:id])
  @model.destroy
  head :ok
end

- (Object) fits_content(type, content_type)



66
67
68
69
70
71
# File 'lib/restfulie/server/controller.rb', line 66

def fits_content(type, content_type)
  Restfulie::MediaType.supports?(content_type) &&
          (type.respond_to?(:media_type_representations) ?
          type.media_type_representations.include?(content_type) :
          Restfulie::MediaType.default_representations.include?(content_type))
end

- (Object) model_name

retrieves the model name



62
63
64
# File 'lib/restfulie/server/controller.rb', line 62

def model_name
  self.class.name[/(.*)Controller/,1].singularize.underscore
end

- (Object) model_type

returns the model for this controller



57
58
59
# File 'lib/restfulie/server/controller.rb', line 57

def model_type
  self.class.name[/(.*)Controller/,1].singularize.constantize
end

- (Object) model_variable_name



26
27
28
# File 'lib/restfulie/server/controller.rb', line 26

def model_variable_name
  ("@" + model_type.to_s.downcase).to_sym
end

- (Object) show

renders this resource



20
21
22
23
24
# File 'lib/restfulie/server/controller.rb', line 20

def show
  @model = model_type.find(params[:id])
  instance_variable_set(model_variable_name, @model)
  render_resource(@model)
end

- (Object) update

updates a resouce



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/restfulie/server/controller.rb', line 38

def update
  type = model_type

  @loaded = type.find(params[:id])
  return head(:status => 405) unless @loaded.can? :update

  return head(415) unless fits_content(type, request.headers['CONTENT_TYPE'])

  @model = Hash.from_xml(request.body.string)[model_name]
  pre_update(@model) if self.respond_to?(:pre_update)
  
  if @loaded.update_attributes(@model)
    render_resource @loaded
  else
    render :xml => @loaded.errors, :status => :unprocessable_entity
  end
end