Upgrading from rails 2 router to rails 3 while keeping :collection and :member

We are just upgrading our router from rails 2 to 3 and wanted to keep resource :member => {:foo => :get} working so we do not have to rewrite everything at once and can roll out the change and then refactor in a separate step.

Usage

# use this
resources :users, :member => {:invite => :post}, :collection => {:search => :get}

# instead of
resources :users, :member => {:invite => :post}, :collection => {:search => :get} do
  member do
   post :invite
  end
  collection do
    get :search
  end
end

Code

# keep resource with :member / :collection working to reduce diff
ActionDispatch::Routing::Mapper.class_eval do
  def resources(*args, &block)
    block = support_deprecated_options(args, block)
    super(*args, &block)
  end

  def resource(*args, &block)
    block = support_deprecated_options(args, block)
    super(*args, &block)
  end

  private

  def support_deprecated_options(args, original_block)
    options = args.last
    if options.is_a?(Hash) && (options[:member] || options[:collection])
      collection = options.delete(:collection)
      member = options.delete(:member)
      Proc.new do
        collection { add_deprecated_actions(collection) } if collection
        member { add_deprecated_actions(member) } if member
        original_block.call if original_block
      end
    else
      original_block
    end
  end

  def add_deprecated_actions(collection)
    collection.each { |name, method| match name, :via => (method == :any ? nil : method) }
  end
end
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s