views:

374

answers:

2

Hello,

I have some rails resources with complementary parameters to the :id one. For example :

map.resources :users, :controller => 'users', :path_prefix => ':lang'

So that I'd have the lang prefixed to the URL.
The default generated url methods would be :

user_url(lang, user)

However the lang is always the same parameter. For example params[:lang] or user.lang. So I'd be looking for a clean way to define this lang parameter without passing it in the user_url method parameters.
Until now I'm using helpers. But redefining all those methods is not very clean. And an helper is not valid in the controller when the user_url method should be.

I did also try to add them to a lib module so that they'd be available in the controller and in the view. However I see then a problem with rspec. Even though I include the library, the methods used are the rails defaultly generated ones.

Would you have any idea how I could clear that up ? :p

+1  A: 

Try this:

module UserWithLanguageSupport
  def user_url(user, options = {})
    url_for options.reverse_merge({
              :id => @user,
              :lang => params.fetch(:lang, @user.lang)
            })
  end
end

class MyController < ActionController::Base

  include UserWithLanguageSupport
  helper :all, UserWithLanguageSupport

end
James A. Rosen
Yes, just re-write the named route function.
ndp
Well adding it to the controller isn't a good idea ;)But I've tried to add it to a lib module which I include in ApplicationController.However weirdly enough the default method overrites this in RSpec. So my tests doesn't happens well when they should.That's why I was hoping for something a bit better.
Damien MATHIEU
I'm for skinny controllers, so putting into a module that your ApplicationController both includes and sets as a helper works great. It doesn't make the Controller any smaller _conceptually_, but it does literally.
James A. Rosen
+1  A: 

You can try using an alias_method_chain (Yehuda would probably say it's abusing, though :)). Add your param value to the options and then call the original method.

neutrino
Yeah I like that one :)
Damien MATHIEU