我正在尝试使用Ruby on Rails构建cms应用程序4.为了得到合适的控制器。我需要在使用它之前对查询字符串进行预处理 在匹配方法中如下所示
# config/routes.rb
Cms::Application.routes do
varparameter=ENV["QUERY_STRING"]
@controller=preprocessqstring(varparameter)
match '/cms/home', to: 'login#show', via: [:get, :post]
match 'cms/:content(/:action(/:id(.:format)))',to: @controller+'#show', via: [:get, :post]
end
设置ENV [" QUERY_STRING"]我正在使用以下机架中间件
# lib/httpvariables.rb
require 'rack'
class Httpvariables
def initialize(app)
@app = app
end
def call(env)
@status, @headers, @response = @app.call(env)
request=Rack::Request.new(env)
ENV["REQUEST_URI"]=request.env["REQUEST_URI"]
ENV["QUERY_STRING"]=request.env["QUERY_STRING"]
ENV["SERVER_PORT"]=request.env["SERVER_PORT"]
ENV["SERVER_PROTOCOL"]=request.env["SERVER_PROTOCOL"]
[@status, @headers, self]
end
end
我在application.rb
中添加了这一行# config/application.rb
config.middleware.use Rack::Httpvariables
令我惊讶的是,如果尝试启动rails服务器它的显示失败:
mundile@mundile-HP:~/RoR-workspace/workspace/cms$ rails server
=> Booting WEBrick
=> Rails 4.1.1 application starting in development on http://0.0.0.0:3000
=> Run `rails server -h` for more startup options
=> Notice: server is listening on all interfaces (0.0.0.0). Consider using 127.0.0.1 (--binding option)
=> Ctrl-C to shutdown server
Exiting
/home/mundile/RoR-workspace/workspace/cms/config/routes.rb:68:in `block in <top (required)>': undefined method `+' for nil:NilClass (NoMethodError)
我需要你的帮助来确定问题的原因。似乎ENV["QUERY_STRING"]
给出了零,但为什么呢?感谢。
答案 0 :(得分:0)
我将中间件代码更改为:
# lib/httpvariables.rb
require 'rack'
class Httpvariables
def initialize(app)
@app = app
end
def call(env)
request=Rack::Request.new(env)
ENV["REQUEST_URI"]=request.env["REQUEST_URI"]
ENV["QUERY_STRING"]=request.env["QUERY_STRING"]
ENV["SERVER_PORT"]=request.env["SERVER_PORT"]
ENV["BASE_URL"]=request.base_url
@app.call(env)
end
end
这就像魅力一样 我还使用此代码回答了这个问题:Rails access request in routes.rb for dynamic routes