【问题标题】:How to use rack middleware with Rails3?如何在 Rails3 中使用机架中间件?
【发布时间】:2010-11-19 12:22:25
【问题描述】:

大家好, 我正在尝试使机架中间件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 路由器处理它,但这是一个实验,我只是玩得开心:-)

谢谢!

【问题讨论】:

  • 为什么不使用 Rails 系统。小东西比较复杂。
  • 你应该阅读整个问题,我的意思是直到最后......“ps:我知道我可以用 rails3 路由器处理它,但这是一个实验,我只是玩得开心”

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


【解决方案1】:

当没有路由匹配时,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

【讨论】:

  • 嘿,谢谢你的回复,我现在感觉很笨:-)
  • 你知道在 ApplicationController 中使用中间件与救援相比有什么优势吗?
  • 不确定你的意思。您可能想通过一些示例代码提出一个新问题?不过,一般来说,最好让 Rails 处理异常,并设置它以在出现问题时通知您。有关示例,请参见 hoptoadapp.com。
猜你喜欢
  • 1970-01-01
  • 2011-03-18
  • 2011-04-19
  • 1970-01-01
  • 2012-02-07
  • 1970-01-01
  • 2022-10-20
  • 2011-08-09
  • 1970-01-01
相关资源
最近更新 更多