Skip to content

Instantly share code, notes, and snippets.

@rurounijones
Forked from be9/acl9_query_by_role.rb
Created June 7, 2009 07:35
Show Gist options
  • Save rurounijones/125233 to your computer and use it in GitHub Desktop.
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
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