如何使用Rails3的机架中间件?

时间:2010-11-19 12:22:25

标签: ruby-on-rails ruby-on-rails-3 rack

嘿伙计们, 我正在尝试使机架中间件NotFound与rails3一起工作,但我需要进行一些更改才能返回一些json,所以我基本上定义了一个新类:

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文件中:

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

现在......好吧,它按照我的预期工作......总是返回

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

现在,只有路由器出现故障,我才能让它工作?我看到有一个insert_after方法,但在Application.routes

之后无法实现 ps:我知道我可以使用rails3路由器处理它,但这是一个实验,我只是有一些乐趣: - )

谢谢!

1 个答案:

答案 0 :(得分: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