[LRUG] Setting default roles in a user record

Craig Webster craig at xeriom.net
Tue Aug 7 04:04:03 PDT 2007


On 7 Aug 2007, at 11:25, John Winters wrote:
> This sounds a promising approach.  Could I just override the default
> "new" method with my own which sets default values if no parameters  
> are
> passed in?

If you're using a newish version of active support you should be able  
to do something like this (untested):

class User
   class << self
     # Build a new user with default roles.
     #
     def new_with_default_roles(*args)
       user = new_without_default_roles(*args)
       user.roles += Role.default_roles
       user
     end
     alias_method_chain :new, :default_roles
   end
end

Each call to User.new will now return a user with default roles (as  
defined by Role#default_roles).

With an older version of active support, you'll need to use (gasp)  
two alias_method calls:
   alias_method :new_without_default_roles, :new
   alias_method :new, :new_with_default_roles

I'd love to hear of improvements on this pattern :)

Cheers,
Craig
--
Craig Webster   | Lead Developer   | skype: craigwebster
Xeriom Networks | t: 0131 208 3800 | w: http://xeriom.net/

   -- Virtual machines, dedicated servers and colocation --

Xeriom Networks Limited.
94/1 Spring Gardens, Abbeyhill, Edinburgh, Scotland.
Registered in England and Wales. Company No. 5961686.

All agreements are made under our standard terms and conditions.  
These can
be found at http://xeriom.net/terms_and_conditions





More information about the Chat mailing list