Dynamic Rails routing based on database

后端 未结 2 1502
梦谈多话
梦谈多话 2021-02-04 19:54

I\'m building a CMS with various modules (blog, calendar, etc.) using Rails 2.3. Each module is handled by a different controller and that works just fine.

The only prob

2条回答
  •  灰色年华
    2021-02-04 19:58

    This problem can be solved with some Rack middleware:

    This code in lib/root_rewriter.rb:

    module DefV
      class RootRewriter
        def initialize(app)
          @app = app
        end
    
        def call(env)
          if env['REQUEST_URI'] == '/' # Root is requested!
            env['REQUEST_URI'] = Page.find_by_root(true).uri # for example /blog/
          end
    
          @app.call(env)
        end
      end
    end
    

    Then in your config/environment.rb at the bottom

    require 'root_rewriter'
    ActionController::Dispatcher.middleware.insert_after ActiveRecord::QueryCache, DefV::RootRewriter
    

    This middleware will check if the requested page (REQUEST_URI) is '/' and then do a lookup for the actual path (Implementation to this is up to you ;-)). You might do good on caching this info somewhere (Cache.fetch('root_path') { Page.find... })

    There are some problems with checking REQUEST_URI, since not all webservers pass this correctly. For the whole implementation detail in Rails see http://api.rubyonrails.org/classes/ActionController/Request.html#M000720 (Click "View source")

提交回复
热议问题