How to dynamically add routes in Rails 3.2

不问归期 提交于 2019-12-13 19:14:56

问题


I'm using acts_as_commentable in a Rails app to allow commenting on different types of models.

I've got a polymorphic CommentsController ala the Polymorphic Association Railscast.

I'm trying to write specs for this controller; however, I'd like to use acts_as_fu to define a generic Commentable class for the controller to use in the specs. This way its not tied to one of our concrete commentable models.

The problem is that when I try to test the controller actions I get routing errors because there are no routes for the Commentable class I created using acts_as_fu.

I need a way to draw the routes for this dynamically created model in a before(:all) (using RSpec by the way) for the specs.

Here's what my spec looks like so far:

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

UPDATE: Found a 'hacky' solution. I'm wondering if there's a cleaner way of doing this though.


回答1:


Found a solution for adding routes at runtime in Rails 3, albeit a hacky one:

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


来源:https://stackoverflow.com/questions/18706713/how-to-dynamically-add-routes-in-rails-3-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!