-
-
Save rurounijones/125233 to your computer and use it in GitHub Desktop.
Using method_missing to dynamically create subject listing for objects based on role
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 DynamicFinderMatch | |
attr_accessor :attribute | |
def initialize(method_sym) | |
if Role.all(:select => 'name').map{|n| n.name.pluralize}.include?(method_sym.to_s) | |
@attribute = method_sym | |
end | |
end | |
def match? | |
@attribute != nil | |
end | |
end | |
class Committee < ActiveRecord::Base | |
acts_as_authorization_object | |
validates_presence_of :name | |
def method_missing(method_sym, *arguments, &block) | |
match = DynamicFinderMatch.new(method_sym) | |
if match.match? | |
self.class.class_eval <<-EOF, __FILE__, __LINE__ | |
def #{method_sym} | |
corresponding_role_ids = self.accepted_roles.all(:select => 'id', :conditions => { :name => '#{method_sym.to_s.singularize}' }).map(&:id) | |
return User.all(:include => :roles, :conditions => ['roles.id IN (?)', corresponding_role_ids]) | |
end | |
EOF | |
send method_sym | |
else | |
super | |
end | |
end | |
def respond_to?(method_sym, include_private = false) | |
if DynamicFinderMatch.new(method_sym).match? | |
true | |
else | |
super | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment