Created
August 9, 2011 03:45
-
-
Save mongrelion/1133363 to your computer and use it in GitHub Desktop.
Dynamic Role methods for Role and User models
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
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
why send instead of send ?