Skip to content

Instantly share code, notes, and snippets.

@mongrelion
Created August 9, 2011 03:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mongrelion/1133363 to your computer and use it in GitHub Desktop.
Save mongrelion/1133363 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
@guilleiguaran
Copy link

why send instead of send ?

@mongrelion
Copy link
Author

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