Skip to content

Instantly share code, notes, and snippets.

@fayimora
Forked from mongrelion/role.rb
Created February 12, 2012 18:19
Show Gist options
  • Save fayimora/1810009 to your computer and use it in GitHub Desktop.
Save fayimora/1810009 to your computer and use it in GitHub Desktop.
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
@fayimora
Copy link
Author

SO why do you have 2 models, Role and User? I thought u said just a string column..

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment