How to use rack middleware with Rails3?
Hey guys, I'm trying to make the rack middleware NotFound to work with rails3 but I needed to make some changes to return some json, so I basically defined a new class :
class NotFound
def initialize(app, msg, content_type = "text/html")
@app = app
@content = msg
@length = msg.size.to_s
@content_type = content_type
end
def call(env)
[404, {'Content-Type' => @content_type, 'Content-Length' => @length}, @content]
end
end
I added this class above to "app/middleware/not_found.rb" and add this line below to my application.rb file :
config.middleware.use "NotFound", {:error => "Endpoint Not Found"}.to_json, "application/json"
and now ... well, it works as I expected ... It always return
{"error"=>"Endpoint Not Found"}
Now how can I make it work only if the router fails ? I saw there is a insert_after method but can't make it happen after Application.routes
ps : I know I could handle it with the rails3 router, but it's an experiment, I'm just having some fun :-)开发者_开发知识库
Thanks !
The Rails router will already return a 404 response when no routes match. If you want to customize that response, I suppose you could do:
class NotFound
def initialize(app, msg, content_type = "text/html")
@app = app
@content = msg
@length = msg.size.to_s
@content_type = content_type
end
def call(env)
status, headers, body = @app.call(env)
if status == 404
[404, {'Content-Type' => @content_type, 'Content-Length' => @length}, @content]
else
[status, headers, body]
end
end
end
精彩评论