Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Dynamic Role methods for Role and User models
class Role < ActiveRecord::Base
ROLES = [ :group_admin, :agency_admin ]
# - Relationships -
has_many :user_roles
has_many :users, :through => :user_roles
# - Class Methods -
class << self
ROLES.each do |role|
define_method( role ) do
find_by_name role.to_s.camelcase
end
end
end
end
class User < ActiveRecord::Base
# - Relationships -
has_many :user_roles
has_many :roles, :through => :user_roles
# - Instance Methods -
Role::ROLES.each do |role|
define_method "#{ role }?" do
role? Role.__send__( role )
end
end
end
@guilleiguaran

This comment has been minimized.

Copy link

guilleiguaran commented Aug 9, 2011

why send instead of send ?

@mongrelion

This comment has been minimized.

Copy link
Owner Author

mongrelion commented Aug 9, 2011

Because I want to keep it as isolated as possible. Perhaps someday I'll have to declare any method with name 'send', and it'll clash.
http://ruby-doc.org/core/classes/Object.src/M000999.html
However, 'send' is fancier than 'send'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.