Class: Servme::Responder

Inherits:
Object
  • Object
show all
Defined in:
lib/servme/responder.rb

Constant Summary collapse

DEFAULT_HEADERS =
{
  'Content-Type' => 'application/json'
}
DEFAULT_OPTIONS =
{
  :static_file_root_path => "dist",
  :static_file_vdir => //
}

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(sinatra_app, opts) ⇒ Responder

Returns a new instance of Responder.



15
16
17
18
# File 'lib/servme/responder.rb', line 15

def initialize(sinatra_app, opts)
  @sinatra_app = sinatra_app
  @options = DEFAULT_OPTIONS.merge(opts.reject { |k,v| v.nil? })
end

Instance Attribute Details

#optionsObject

Returns the value of attribute options.



13
14
15
# File 'lib/servme/responder.rb', line 13

def options
  @options
end

#sinatra_appObject

Returns the value of attribute sinatra_app.



13
14
15
# File 'lib/servme/responder.rb', line 13

def sinatra_app
  @sinatra_app
end

Instance Method Details

#default_response(request) ⇒ Object



50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/servme/responder.rb', line 50

def default_response(request)
  {
    :headers => DEFAULT_HEADERS,
    :status_code => 404,
    :data => {
      :error => "Servme doesn't know how to respond to this request",
      :request => {
        :method => request.request_method.downcase.to_sym, #FIXME: duplication -- stubber.rb
        :params => request.params,
        :path => request.path
      }
    }
  }
end

#format_response(response) ⇒ Object



41
42
43
44
# File 'lib/servme/responder.rb', line 41

def format_response(response)
  body = json?(response) ? JSON::dump(response[:data]) : response[:data]
  [response[:status_code], response[:headers], body]
end

#json?(response) ⇒ Boolean

Returns:

  • (Boolean)


46
47
48
# File 'lib/servme/responder.rb', line 46

def json?(response)
  response[:headers]['Content-Type'] == 'application/json'
end

#respond(request) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/servme/responder.rb', line 24

def respond(request)
  process_json_request(request)
  relative_path_on_disk = request.path.sub(options[:static_file_vdir], '')

  static_file = File.join(options[:static_file_root_path], relative_path_on_disk)
  stub = stubber.stub_for_request(request)
  if (stub)
    format_response(stub)
  elsif(request.path == '/')
    sinatra_app.send_file("#{options[:static_file_root_path]}/index.html")
  elsif(File.exists?(static_file))
    sinatra_app.send_file(static_file)
  else
    format_response(default_response(request))
  end
end

#stubberObject



20
21
22
# File 'lib/servme/responder.rb', line 20

def stubber
  Stubber.instance
end