Skip to content

Instantly share code, notes, and snippets.

@gaspard
Created October 15, 2009 01:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gaspard/210544 to your computer and use it in GitHub Desktop.
Save gaspard/210544 to your computer and use it in GitHub Desktop.
# 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