【问题标题】:How to dynamically add routes in Rails 3.2如何在 Rails 3.2 中动态添加路由
【发布时间】:2013-09-09 20:44:07
【问题描述】:

我在 Rails 应用程序中使用acts_as_commentable 来允许评论不同类型的模型。

我有一个多态的CommentsController ala Polymorphic Association Railscast

我正在尝试为这个控制器编写规范;但是,我想使用acts_as_fu 定义一个通用的Commentable 类,供控制器在规范中使用。这样它就不会与我们的具体可评论模型之一绑定。

问题是,当我尝试测试控制器操作时出现路由错误,因为我使用acts_as_fu 创建的Commentable 类没有路由。

我需要一种方法在 before(:all)(顺便使用 RSpec)中为这个动态创建的模型绘制路线,以获取规范。

到目前为止,我的规范如下所示:

describe CommentsController do
  before(:all) do
    # Using acts_as_fu to create generic Commentable class
    build_model :commentable do
      acts_as_commentable :comment
      belongs_to :user
      attr_accessible :user
    end

    # TODO - Initialize Commentable routes
  end
end

更新:找到了一个“hacky”解决方案。我想知道是否有更清洁的方法来做到这一点。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 rspec acts-as-commentable


    【解决方案1】:

    adding routes at runtime in Rails 3 找到了一个解决方案,虽然很老套:

    describe CommentsController do
      before(:all) do
        # Using acts_as_fu to create generic Commentable class
        build_model :commentable do
          acts_as_commentable :comment
          belongs_to :user
          attr_accessible :user
        end
    
        # Hacky hacky
        begin
          _routes = Rails.application.routes
          _routes.disable_clear_and_finalize = true
          _routes.clear!
          Rails.application.routes_reloader.paths.each{ |path| load(path) }
          _routes.draw do
            # Initialize Commentable routes    
            resources :commentable do
              # Routes for comment management
              resources :comments
            end
          end
          ActiveSupport.on_load(:action_controller) { _routes.finalize! }
        ensure
          _routes.disable_clear_and_finalize = false
        end
      end
    end
    

    【讨论】:

    • 它看起来像一个 Rails 魔法 :) 但我们在项目中使用此功能在 Test Env 中添加一些 hack 路线。
    猜你喜欢
    • 2012-06-07
    • 1970-01-01
    • 2012-05-31
    • 1970-01-01
    • 2014-03-13
    • 2018-07-27
    • 2016-03-22
    • 2021-06-12
    • 1970-01-01
    相关资源
    最近更新 更多