How to use rack middleware with Rails3?

人盡茶涼 提交于 2019-12-06 11:04:32

问题


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 !


回答1:


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


来源:https://stackoverflow.com/questions/4224900/how-to-use-rack-middleware-with-rails3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!