Class: Sinatra::Hat::Responder

Inherits:
Object
  • Object
show all
Defined in:
lib/sinatras-hat/responder.rb

Overview

The responder assigns data to instance variables, then either gets the appropriate response proc and instance_exec’s it in the context of a new Response object, or serializes the data.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(maker) ⇒ Responder

Returns a new instance of Responder.



11
12
13
# File 'lib/sinatras-hat/responder.rb', line 11

def initialize(maker)
  @maker = maker
end

Instance Attribute Details

#makerObject (readonly)

Returns the value of attribute maker.



9
10
11
# File 'lib/sinatras-hat/responder.rb', line 9

def maker
  @maker
end

Instance Method Details

#defaultsObject



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/sinatras-hat/responder.rb', line 15

def defaults
  @defaults ||= {
    :show => {
      :success => proc { |data| render(:show) },
      :failure => proc { |data| redirect('/') }
    },

    :index => {
      :success => proc { |data| render(:index) },
      :failure => proc { |data| redirect('/') }
    },

    :create => {
      :success => proc { |data| redirect(data) },
      :failure => proc { |data| render(:new) }
    },

    :new => {
      :success => proc { |data| render(:new) },
      :failure => proc { |data| redirect('/') }
    },

    :edit => {
      :success => proc { |data| render(:edit) }
    },

    :destroy => {
      :success => proc { |data| redirect(resource_path('/')) }
    },

    :update => {
      :success => proc { |data| redirect(data) },
      :failure => proc { |data| render(:edit) }
    }
  }
end

#failure(name, request, data) ⇒ Object

Called when a request is not able to handled. This could be because a record could not be created or saved.



61
62
63
# File 'lib/sinatras-hat/responder.rb', line 61

def failure(name, request, data)
  handle(:failure, name, request, data)
end

#serialize(request, data) ⇒ Object

Serializes the data passed in, first looking for a custom formatter, then falling back on trying to call to_ on the data. If neither are available, returns an error with the status code 406.



68
69
70
71
72
# File 'lib/sinatras-hat/responder.rb', line 68

def serialize(request, data)
  name = request.params[:format].to_sym
  formatter = to_format(name)
  formatter[data] || request.error(406)
end

#success(name, request, data) ⇒ Object

Called when a request is handled successfully. For most GET requests, this is always the case. For update/create actions, it is when the record is created/updated successfully.



55
56
57
# File 'lib/sinatras-hat/responder.rb', line 55

def success(name, request, data)
  handle(:success, name, request, data)
end