render short circuit?

18 views
Skip to first unread message

Ted Milker

unread,
Aug 20, 2013, 9:29:12 AM8/20/13
to scor...@googlegroups.com
Is there a way to short circuit straight to the render phase?  I was trying to do something like yesterday:

get '/*' do |filename|
  render
:not_found and return unless File.readable? File.join('public', filename)

 
File.read File.join('public', filename)
end

but it doesn't like the return.  Guard clauses are better than an if hierarchy like:

get '/*' do |filename|
 
if File.readable? File.join('public', filename)
   
File.read File.join('public', filename)
 
else
    render
:not_found
 
end
end


This isn't how I would normally serve static files but I needed something simple and fast.  This isn't even how I would do this anymore with scorched but it would be useful to know if I can do it in the future for real things.

Tom Wardrop

unread,
Aug 20, 2013, 7:30:13 PM8/20/13
to scor...@googlegroups.com
You want to use `next` rather than `return`.

In Ruby, when `return` is used within a block, it attempts to return on-behalf of the closest method up the call stack; the method that invoked the block. If there is no method in the call stack, or if the binding of the block is different to the outer method (such as in this case), you get a LocalJumpError. 

Most of the interrupt keywords intended for loops (next, break, redo) can be used in ordinary proc's. 

Tom
Reply all
Reply to author
Forward
0 new messages