For some reason, in a Sinatra "after" filter I can't seem to access the current status code
require 'rubygems'
require 'sinatra'
after do
puts "After hook with code: #{response.status}"
end
get '/hi' do
halt(401, "wtf?")
end
When running curl 127.0.0.1:4567/hi, it results in:
After hook for code: 200
It's basically a function of how the methods are implemented in Sinatra. The methods we need to pay attention to are call!, invoke and dispatch!, all methods in Sinatra::Base (as of v1.3.2).
call! is the top level method, and in there, it calls the following line of code:
invoke { dispatch! }
Now, invoke looks like this:
def invoke
res = catch(:halt) { yield }
res = [res] if Fixnum === res or String === res
if Array === res and Fixnum === res.first
status(res.shift)
body(res.pop)
headers(*res)
elsif res.respond_to? :each
body res
end
end
It actually sets the response code on the basis of the thing you throw with :halt. And dispatch! looks like:
def dispatch!
static! if settings.static? && (request.get? || request.head?)
filter! :before
route!
rescue ::Exception => boom
handle_exception!(boom)
ensure
filter! :after unless env['sinatra.static_file']
end
See that ensure block? That gets run as the :halt symbol that has been thrown sails up the stack trace. Crucially, this is before the status setting code is run.
Related
require_relative 'config/environment'
HTTP_ERRORS = [
RestClient::Exception
]
module API
class Client
def initialize
#client = RawClient.new
end
def search(params = {})
call { #client.search(params) }
end
def call
raise 'No block specified' unless block_given?
loop do # Keep retrying on error
begin
return yield
rescue *HTTP_ERRORS => e
puts "#{e.response&.request.url}"
sleep 5
end
end
end
end
class RawClient
BASE_URL = 'https://www.google.com'
def search(params = {})
go "search/#{params.delete(:query)}", params
end
private
def go(path, params = {})
RestClient.get(BASE_URL + '/' + path, params: params)
end
end
end
API::Client.new.search(query: 'tulips', per_page: 10)
Will output
https://www.google.com/search/tulips?per_page=10 # First time
https://www.google.com/search/?per_page=10 # On retry
I thought I was being clever here: have a flexible and unified way to pass parameters (ie. search(query: 'tulips', per_page: 10)) and let the client implementation figure out what goes into the url itself (ie. query) and what should be passed as GET parameters (ie. per_page).
But the query param is lost from the params after the first retry, because the hash is passed by reference and delete makes a permanent change to it. The second time yield is called, it apparently preserves the context and params won't have the deleted query anymore in it.
What would be an elegant way to solve this? Doing call { #client.search(params.dup) } seems a bit excessive.
I have a Rack web server app to validate in call(env) the provided HTTP query string and return different responses immediately (with appropriate erb) if those bits of validations fail.
I'm calling the following method to provide a response:
def respond(http_status, http_headers, html_body = '')
# Provide HTTP response
html_body = yield if block_given?
[http_status, http_headers, [html_body]]
end
which I gleaned from the web.
I'm then calling respond(...) from different points inside my call(env) method rather like this:
def call(env)
case blah
when '/'
if validation_a_fails
respond(invalid_a)
else
set up a variable for later use...
end
if validation_b_fails
respond(invalid_b)
else
set up another variable for later use...
end
if validation_c_fails
respond(invalid_c)
else
set up something else for later use...
end
else # not root url
respond(404_situation)
end
end
end
I expected that a call to respond(invalid_a) would exit the call method immediately. However, it doesn't. Instead, the rest of the call method are executed.
How can I get the respond(...) to return immediately to the calling browser?
if validation_a_fails
return respond(invalid_a)
else
in your case you can't omit return because you have multiple if-elses so it'd go through them.
# users_show_controller.rb
class Controllers::Users::Show
include Hanami::Action
params do
required(:id).filled(:str?)
end
def call(params)
result = users_show_interactor(id: params[:id])
halt 404 if result.failure?
#user = result.user
end
end
# users_show_interactor.rb
class Users::Show::Interactor
include Hanami::Interactor
expose :user
def call(:id)
#user = UserRepository.find_by(:id)
end
end
I have a controller and a interactor like above.
And I'm considering the better way to distinguish ClientError from ServerError, on the controller.
I think It is nice if I could handle an error like below.
handle_exeption StandardError => :some_handler
But, hanami-interactor wraps errors raised inside themselves and so, controller receive errors through result object from interactor.
I don't think that re-raising an error on the controller is good way.
result = some_interactor.call(params)
raise result.error if result.failure
How about implementing the error handler like this?
I know the if statement will increase easily and so this way is not smart.
def call(params)
result = some_interactor.call(params)
handle_error(result.error) if result.faulure?
end
private
def handle_error(error)
return handle_client_error(error) if error.is_a?(ClientError)
return server_error(error) if error.is_a?(ServerError)
end
Not actually hanami-oriented way, but please have a look at dry-monads with do notation. The basic idea is that you can write the interactor-like processing code in the following way
def some_action
value_1 = yield step_1
value_2 = yield step_2(value_1)
return yield(step_3(value_2))
end
def step_1
if condition
Success(some_value)
else
Failure(:some_error_code)
end
end
def step_2
if condition
Success(some_value)
else
Failure(:some_error_code_2)
end
end
Then in the controller you can match the failures using dry-matcher:
matcher.(result) do |m|
m.success do |v|
# ok
end
m.failure :some_error_code do |v|
halt 400
end
m.failure :some_error_2 do |v|
halt 422
end
end
The matcher may be defined in the prepend code for all controllers, so it's easy to remove the code duplication.
Hanami way is validating input parameters before each request handler. So, ClientError must be identified always before actions logic.
halt 400 unless params.valid? #halt ClientError
#your code
result = users_show_interactor(id: params[:id])
halt 422 if result.failure? #ServerError
halt 404 unless result.user
#user = result.user
I normally go about by raising scoped errors in the interactor, then the controller only has to rescue the errors raised by the interactor and return the appropriate status response.
Interactor:
module Users
class Delete
include Tnt::Interactor
class UserNotFoundError < ApplicationError; end
def call(report_id)
deleted = UserRepository.new.delete(report_id)
fail_with!(UserNotFoundError) unless deleted
end
end
end
Controller:
module Api::Controllers::Users
class Destroy
include Api::Action
include Api::Halt
params do
required(:id).filled(:str?, :uuid?)
end
def call(params)
halt 422 unless params.valid?
Users::Delete.new.call(params[:id])
rescue Users::Delete::UserNotFoundError => e
halt_with_status_and_error(404, e)
end
end
end
fail_with! and halt_with_status_and_error are helper methods common to my interactors and controllers, respectively.
# module Api::Halt
def halt_with_status_and_error(status, error = ApplicationError)
halt status, JSON.generate(
errors: [{ key: error.key, message: error.message }],
)
end
# module Tnt::Interactor
def fail_with!(exception)
#__result.fail!
raise exception
end
I'm looking for ways to DRY my Sinatra app and have run into some scoping issues -- in particular, helpers and Sinatra functions are not available inside my handlers. Can someone please tell me if there's a way to fix this code and more importantly, what is going on?
Thank you.
require 'sinatra'
require 'pp'
helpers do
def h(txt)
"<h1>#{txt}</h1>"
end
end
before do
puts request.path
end
def r(url, get_handler, post_handler = nil)
get(url){ get_handler.call } if get_handler
post(url){ post_handler.call } if post_handler
end
routes_composite_hash = {
'/' => lambda{ h('index page'); pp params }, #can't access h nor params!!!
'/login' => [lambda{'login page'}, lambda{'login processing'}],
'/postonly' => [nil, lambda{'postonly processing'}],
}
routes_composite_hash.each_pair do |k,v|
r(k, *v)
end
Interesting!
Do this:
def r(url, get_handler, post_handler = nil)
get(url, &get_handler) if get_handler
post(url, &post_handler) if post_handler
end
routes_composite_hash = {
'/' => lambda{ h('index page'); pp params },
'/login' => [lambda{'login page'}, lambda{'login processing'}],
'/postonly' => [nil, lambda{'postonly processing'}],
}
routes_composite_hash.each_pair do |k,v|
r(k, *v)
end
As Kashyap explains, you were calling your get and post handlers inside the main context. This just converts sent lambda to a block and passes it to the desired method.
The methods you define inside helpers do .. end blocks are available only inside routes and filters and views contexts and thus, since you are not using them inside any of those, it won't work. Lambdas preserve the execution context which means that in the hash {'/' => lambda { h }..}, the context is main but inside the get method, the context changes and the helpers are available only in this context.
To achieve what you want to do though, (although I would suggest you avoid doing this), you can just define the helpers as lambdas inside your app file itself. In your case, it would be:
def h(txt)
"<h1>#{txt}</h1>"
end
# And then the rest of the methods and the routes hash
This way, the h method is in the context of the main object and thus will be visible all over.
I got a NoMethodError when trying to return a response in Sinatra. This is the error:
NoMethodError at /contact/book-me.php
undefined method `body=' for #<String:0x00000001911418>
/home/kerrick/.rvm/gems/ruby-1.9.3-p194/gems/sinatra-1.3.2/lib/sinatra/base.rb in body
response.body = value
/home/kerrick/.rvm/gems/ruby-1.9.3-p194/gems/sinatra-1.3.2/lib/sinatra/base.rb in invoke
body res
/home/kerrick/.rvm/gems/ruby-1.9.3-p194/gems/sinatra-1.3.2/lib/sinatra/base.rb in call!
invoke { dispatch! }
/home/kerrick/.rvm/gems/ruby-1.9.3-p194/gems/sinatra-1.3.2/lib/sinatra/base.rb in call
dup.call!(env)
/home/kerrick/.rvm/gems/ruby-1.9.3-p194/gems/rack-protection-1.2.0/lib/rack/protection/xss_header.rb in call
status, headers, body = #app.call(env)
[...]
This is the relevant code:
# Snipped, but basically populate the #error hash if the form wasn't filled out right
if #error.length == 0
#Snipped, but basically handle the success case
else
#response = ''
#error.each do |x, y|
#response << "<li>#{y}</li> \n"
end
return [400, #response]
end
Why is this happening?
Using #response as your return value in Sinatra is what's causing your problem. The same problem is documented on the Ruby on Rails OldWiki, so it's not just Sinatra specific. You should change your code to look something like this and it'll work:
else
#send_errors = ''
#error.each do |x, y|
#send_errors << "<li>#{y}</li> \n"
end
return [400, #send_errors]
end