【发布时间】:2011-03-14 05:06:31
【问题描述】:
我正在编写一个小应用程序,以便从总体上学习 ruby 和 Web 开发。该应用程序是一个小博客,Web 服务器是杂种。我在 mongrel 之上建立了一个简单的 MVC 结构,带有一个前端控制器和一个 url 调度程序。当我第一次访问urlhttp://myapp/article/show/hello时,显示“你好”文章的内容。
但是从那时起,当我刷新页面或转到另一个 url 时,我看到的是我设置的 404 错误页面。我发现解决问题的唯一方法是为每个请求重新启动服务器,这显然不是解决方案!
我的代码如下所示:
launch.rb
require 'rubygems'
require 'mongrel'
require 'config/settings'
require File.join(Settings::UTILS_DIR, "dispatcher.rb")
class FrontController < Mongrel::HttpHandler
def process(request, response)
route = Dispatcher.new.dispatch(request.params["REQUEST_URI"])
controller = route["class"]
action = route["method"]
params = route["params"]
action_output = controller.new.send(action, params)
response.start(200) do |head, out|
head["Content-Type"] = "text/html"
out << action_output
end
end
end
h = Mongrel::HttpServer.new("192.168.0.103", "3000")
h.register("/", FrontController.new)
h.run.join
dispatcher.rb
require File.join(Settings::CONFIG_DIR, "controllers.rb")
class Dispatcher
def dispatch(uri)
uri = uri.split("/")
if uri.size == 0
return {"class" => Controllers.const_get(:ArticleActions), "method" => :index, "params" => nil}
end
route = {}
unless uri[1].nil? and uri[2].nil?
controller_class = uri[1].capitalize << "Actions" # All controllers classes follow this form : ControllerActions
controller_method = uri[2]
route["class"] = Controllers.const_defined?(controller_class) ? Controllers.const_get(controller_class) : nil
route["method"] = ( route["class"] and route["class"].method_defined?(controller_method) ) ? controller_method : nil
route["params"] = uri.slice(3, uri.size) ? uri.slice(3, uri.size) : nil
end
# If url not valid
if route["class"].nil? or route["method"].nil?
route["class"] = Controllers.const_get(:ErrorActions)
route["method"] = :error404
route["params"] = nil
end
route
end
end
要启动应用程序和服务器,我只需执行 ruby launch.rb。 从昨晚开始,我的头就疼。任何想法 ? 谢谢。
【问题讨论】: