Class: Servme::Responder
- Inherits:
-
Object
- Object
- Servme::Responder
- 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
-
#options ⇒ Object
Returns the value of attribute options.
-
#sinatra_app ⇒ Object
Returns the value of attribute sinatra_app.
Instance Method Summary collapse
- #default_response(request) ⇒ Object
- #format_response(response) ⇒ Object
-
#initialize(sinatra_app, opts) ⇒ Responder
constructor
A new instance of Responder.
- #json?(response) ⇒ Boolean
- #respond(request) ⇒ Object
- #stubber ⇒ Object
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
#options ⇒ Object
Returns the value of attribute options.
13 14 15 |
# File 'lib/servme/responder.rb', line 13 def @options end |
#sinatra_app ⇒ Object
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
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([:static_file_vdir], '') static_file = File.join([: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("#{[: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 |
#stubber ⇒ Object
20 21 22 |
# File 'lib/servme/responder.rb', line 20 def stubber Stubber.instance end |