ruby - Create single method in Rails that handles multiple method names? -


is possible dry-up following code:

def is_user?   is_role? roles[:user] end  def is_mod?   is_role? roles[:mod] end  def is_admin?   is_role? roles[:admin] end  private  def is_role?(role)   self.roles & role == role end 

into single function, yet still have ability call function names (is_user?, is_mod?, etc)

update:

using aetherus' answer below created following managing user roles (where user can have multiple roles):

class user < activerecord::base   # use bitwise values more roles (double previous values)   roles = { user: 1, dummy: 2, mod: 4, admin: 8 }     # add desired role   def add_role(role)     self.roles |= roles[role]   end   # eg: add_role :admin    # removed desired role   def remove_role(role)     self.roles &= ~roles[role]   end    # methods each role (mod? admin? etc)   roles.keys.each |role|     define_method("#{role}?")       self.roles & roles[role] == roles[role]     end   end end 

you can define multiple methods 1 single ruby code block.

%w(user mod admin).each |role|   class_eval <<-ruby, __file__, __line__ + 1     def #{role}?       role == '#{role}' && roles.include?('#{role}')     end   ruby end 

or more clear way:

%w(user mod admin).each |role|   define_method("#{role}?")     self.role == role && roles.include?(role)   end end 

by way, in ruby, is_ prefix not needed, since trailing ? tells programmers method returns true or false.


Comments

Popular posts from this blog

python - Healpy: From Data to Healpix map -

c - Bitwise operation with (signed) enum value -

xslt - Unnest parent nodes by child node -