Created
February 5, 2010 21:42
-
-
Save joeljunstrom/296289 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
# Usage | |
# @assets = Asset.my_filter(params[:filter]).public.all # works like a charm | |
# @assets = @account.assets.my_filter(params[:filter]).public.paginate({ | |
# :page => (params[:page] || 1) | |
# }) # works BUT (ofc) does not adhere to the @account scope | |
# | |
# initializer | |
ActiveRecord::Base.send :include, Spock::Base::Filterable | |
# some lib file | |
module Spock | |
module Base | |
module Filterable | |
def self.included(base) | |
base.extend ClassMethods | |
end | |
module ClassMethods | |
def my_filter(f) | |
f_name, f_arguments = f.to_s.split(':') | |
f_arguments = f_arguments.to_s.split(',') | |
if f_name && my_available_filters.include?(f_name.to_sym) | |
f_arguments.empty? ? send("filter_#{f_name}".to_sym) : self.scopes["filter_#{f_name}".to_sym].call(self, *f_arguments) | |
else | |
self | |
end | |
end | |
def my_available_filters | |
self.scopes.keys.map { |m| m.to_s }.select do |m| | |
m =~ /^filter_/ | |
end.map { |m| m[7..-1].to_sym } | |
end | |
end | |
end | |
end | |
end | |
# valid filter scopes in a model | |
class Asset < ActiveRecord::Base | |
named_scope(:filter_placed_in, lambda { |group_id| | |
{ | |
:select => "DISTINCT assets.*", | |
:from => "assets", | |
:joins => "LEFT JOIN placements ON placements.asset_id = assets.id", | |
:conditions => "placements.group_id = #{group_id}", | |
:order => "placements.position ASC" | |
} | |
}) | |
named_scope(:filter_date, lambda { |date| | |
{ | |
:conditions => ["created_at = ?", date] | |
} | |
}) | |
named_scope(:filter_date_range, lambda { |start_date, end_date| { :conditions => ["created_at BETWEEN ? and ?", start_date, end_date] } }) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment