2010-11-19 38 views
2

嗨, 我试图使机架中间件NotFound与Rails3中工作,但我需要做出一些改变返回一些JSON,所以我基本上定义一个新的类:如何在Rails3中使用机架中间件?

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 

我加入这个级以上为“应用程序/中间件/ not_found.rb”和下面加入这行到我的application.rb中的文件:

config.middleware.use "NotFound", {:error => "Endpoint Not Found"}.to_json, "application/json" 

现在......嗯,它的工作原理如我所料......它总是返回

{"error"=>"Endpoint Not Found"} 

现在只有当路由器出现故障时,我如何才能使其工作?我看到有一个insert_after方法,但不能使它发生在Application.routes

ps:我知道我可以用rails3路由器来处理它,但它是一个实验,我只是有一些乐趣:-)

谢谢!

+0

为什么不使用rails系统来代替。小东西比较复杂。 – shingara 2010-11-19 13:14:40

+0

你应该读完整个问题,我的意思是直到最后......“ps:我知道我可以用rails3路由器处理它,但这是一个实验,我只是有一些乐趣” – Mike 2010-11-19 13:15:55

回答

2

当没有路由匹配时,Rails路由器将已经返回404响应。如果你想自定义这种回应,我想你可以这样做:

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 
+0

嘿感谢您的回复,我现在觉得愚蠢:-) – Mike 2010-11-22 09:28:09

+0

你知道在ApplicationController中使用中间件vs救援有什么优势吗? – Mike 2010-11-22 09:30:17

+0

不确定你的意思。你可能想问一个新的问题,用一些示例代码?但是,通常情况下,最好让Rails处理异常,只需设置它即可在出现问题时通知您。以hoptoadapp.com为例。 – PreciousBodilyFluids 2010-11-22 19:37:47