2

如何使用 lambda 将路由缓存到变量中,但如何在路由块之外创建它?

在调用 routes.rb 块之前加载的 somefile.rb:

x = lambda do
  namespace :test do

    root to: 'application#index'

    get 'page/:page', to: 'pages#show', as: :page

  end
end

路线.rb:

Rails.application.routes.draw do

  x.call if yep

end

由于某些 DSL 类加载错误,这样的代码不起作用。我真的不明白范围是如何在块内工作的。

4

3 回答 3

2

您可以简单地将您的 lambdadraw直接传递给该方法:

# config/routes.rb
conditional_routes = lambda {
  namespace :test do
    root to: 'application#index'
    match 'page/:page' => 'pages#show', as: :page
  end
}

TestApp::Application.routes.draw do
  # default routes
end

TestApp::Application.routes.draw(&conditional_routes) if yep

在这个例子中,我在同一个文件config/routes.rb

# config/initializers/conditional_routes.rb
module ConditionalRoutes
  def self.routes
    lambda {
      # ...
    }
  end
end

# config/routes.rb
TestApp::Application.routes.draw(&ConditionalRoutes.routes)
于 2012-08-24T01:23:40.023 回答
0

在您的初始化程序中:

class Routes
    attr_accessor :routes

    def initialize(routes)
        @routes = routes
    end

    module Helper
        def test_namespace
            Routes.new(self).create_routes
        end
    end

    def self.install!
        ActionDispatch::Routing::Mapper.send :include, Routes::Helper
    end

    def create_routes
        routes.namespace :test do
            root to: 'application#index'
            get 'page/:page', to: 'pages#show', as: :page
        end
    end
end

Routes.install!

在您的路线中

Rails.application.routes.draw do
    test_namespace if yep
end

我真的不确定它会起作用,但它可能会给你一些想法。

于 2012-08-18T19:14:10.670 回答
0

在 routes.rb中保持明确的路由声明通常是一个好习惯。routes.rb 文件旨在成为您必须查看的唯一位置,以了解如何定义路由。

此外,无需拨打routes.draw两次电话。

路线.rb

TestApp::Application.routes.draw do

  constraints(Yep) do
    namespace :test do
      root to: 'application#index'
      get 'page/:page', to: 'pages#show', as: :page
    end
  end

end

lib/yep.rb

class Yep
  def self.matches?(request)
    # if this returns true, your routes block will be drawn
  end
end
于 2012-08-25T08:13:00.073 回答