Created
October 15, 2009 01:04
-
-
Save gaspard/210544 to your computer and use it in GitHub Desktop.
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
# real world example in zena: http://github.com/zena/zena/blob/master/lib/zena/acts/secure.rb | |
# in a module that you include where you need to find | |
def filter_fields(klass) | |
scope = {} | |
find_scope = scope[:find] = {} | |
find_scope[:select] = klass.fields_for(Thread.current.visitor).map {|f| "#{klass.table_name}.#{f}"}.join(',') | |
klass.send(:with_scope, scope) { yield } | |
end | |
# in the class | |
class Product < ActiveRecord::Base | |
def self.fields_for(visitor) | |
if visitor.is_admin? | |
%w{*} | |
else | |
%w{name price category} | |
end | |
end | |
end | |
# usage | |
products = filter_fields(Product) { Product.find(:all, :conditions => ['price > ?', params[:price]]) } | |
# if you do not like this syntax, you could also create a custom finder: | |
class Product < ActiveRecord::Base | |
def self.filter_find(*args) | |
filter_fields(self) { self.find(*args) } | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment