如何在 Rails3 中使用机架中间件? [英] How to use rack middleware with Rails3?
问题描述
大家好,我正在尝试制作机架中间件 NotFound 与 rails3 一起工作,但我需要进行一些更改以返回一些 json,所以我基本上定义了一个新类:
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
我将上面的这个类添加到app/middleware/not_found.rb"并将下面的这一行添加到我的 application.rb 文件中:
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"}
现在我怎样才能让它在路由器出现故障时工作?我看到有一个 insert_after 方法,但在 Application.routes 之后无法实现
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:我知道我可以用 rails3 路由器来处理它,但这是一个实验,我只是玩得开心 :-)
ps : I know I could handle it with the rails3 router, but it's an experiment, I'm just having some fun :-)
谢谢!
推荐答案
当没有路由匹配时,Rails 路由器已经返回 404 响应.如果您想自定义该响应,我想您可以这样做:
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
这篇关于如何在 Rails3 中使用机架中间件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!