Skip to content

Commit

Permalink
Updated searchgasm
Browse files Browse the repository at this point in the history
  • Loading branch information
binarylogic committed Sep 20, 2008
1 parent f818abf commit f8e95aa
Show file tree
Hide file tree
Showing 72 changed files with 116 additions and 55 deletions.
1 change: 1 addition & 0 deletions app/models/user.rb
@@ -1,4 +1,5 @@
class User < ActiveRecord::Base class User < ActiveRecord::Base
belongs_to :user_group belongs_to :user_group
has_one :cool_order, :class_name => "Order", :conditions => {:total => 100}
has_many :orders has_many :orders
end end
@@ -1,3 +1,11 @@
== 1.1.1 released 2008-09-19

* Fixed typo in "next page" button.
* Updated valid options for searching and performing calculations, fixed some bugs when searching and performing calculations with advanced options.
* Fixed bug in ordering where table name was assumed by the hash. Now assumed by the reflection.
* Added default for per_page, so pagination comes implemented by default
* On mass assignments blank strings for *any* conditions are ignored. Sometimes blank strings are meaningful for "equals" and "does not equal", those only takes effect if you explicitly call these conditions: search.conditions.name = "". User.new_search(:conditions => {:name => ""}) will be ignored. Also, Searchgasm should never change how ActiveRecord behaves by default. So User.all(:conditions => {:name => ""}) will NOT be ignored.

== 1.1.0 released 2008-09-18 == 1.1.0 released 2008-09-18


* Added the options :inner_spread and :outer_spread to the page_links helper. Also added various config options for setting page_links defaults. * Added the options :inner_spread and :outer_spread to the page_links helper. Also added various config options for setting page_links defaults.
Expand Down
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
Expand Up @@ -8,7 +8,7 @@ module AssociationCollection
# This needs to be implemented because AR doesn't leverage scopes with this method like it probably should # This needs to be implemented because AR doesn't leverage scopes with this method like it probably should
def find_with_searchgasm(*args) def find_with_searchgasm(*args)
options = args.extract_options! options = args.extract_options!
args << sanitize_options_with_searchgasm(options) args << filter_options_with_searchgasm(options)
find_without_searchgasm(*args) find_without_searchgasm(*args)
end end


Expand Down Expand Up @@ -36,7 +36,7 @@ def build_search!(options = {}, &block)
module Shared module Shared
def count_with_searchgasm(*args) def count_with_searchgasm(*args)
options = args.extract_options! options = args.extract_options!
args << sanitize_options_with_searchgasm(options) args << filter_options_with_searchgasm(options)
count_without_searchgasm(*args) count_without_searchgasm(*args)
end end
end end
Expand Down
Expand Up @@ -6,21 +6,15 @@ module Base
# This is an alias method chain. It hook into ActiveRecord's "calculate" method and checks to see if Searchgasm should get involved. # This is an alias method chain. It hook into ActiveRecord's "calculate" method and checks to see if Searchgasm should get involved.
def calculate_with_searchgasm(*args) def calculate_with_searchgasm(*args)
options = args.extract_options! options = args.extract_options!
options = sanitize_options_with_searchgasm(options) options = filter_options_with_searchgasm(options)
args << options args << options
calculate_without_searchgasm(*args) calculate_without_searchgasm(*args)
end end


def total(*args)
options = args.extract_options!
searcher = searchgasm_searcher(options)
searcher.total
end

# This is an alias method chain. It hooks into ActiveRecord's "find" method and checks to see if Searchgasm should get involved. # This is an alias method chain. It hooks into ActiveRecord's "find" method and checks to see if Searchgasm should get involved.
def find_with_searchgasm(*args) def find_with_searchgasm(*args)
options = args.extract_options! options = args.extract_options!
options = sanitize_options_with_searchgasm(options) options = filter_options_with_searchgasm(options)
args << options args << options
find_without_searchgasm(*args) find_without_searchgasm(*args)
end end
Expand All @@ -45,7 +39,7 @@ def find_with_searchgasm(*args)
# build_search # build_search
# end # end
def with_scope_with_searchgasm(method_scoping = {}, action = :merge, &block) def with_scope_with_searchgasm(method_scoping = {}, action = :merge, &block)
method_scoping[:find] = sanitize_options_with_searchgasm(method_scoping[:find]) if method_scoping[:find] method_scoping[:find] = filter_options_with_searchgasm(method_scoping[:find]) if method_scoping[:find]
with_scope_without_searchgasm(method_scoping, action, &block) with_scope_without_searchgasm(method_scoping, action, &block)
end end


Expand Down Expand Up @@ -130,10 +124,19 @@ def accessible_conditions # :nodoc:
end end


private private
def sanitize_options_with_searchgasm(options = {}) def filter_options_with_searchgasm(options = {})
return options unless Searchgasm::Search::Base.needed?(self, options) return options unless Searchgasm::Search::Base.needed?(self, options)
search = Searchgasm::Search::Base.create_virtual_class(self).new # call explicitly to avoid merging the scopes into the searcher search = Searchgasm::Search::Base.create_virtual_class(self).new # call explicitly to avoid merging the scopes into the searcher
search.acting_as_filter = true search.acting_as_filter = true
conditions = options.delete(:conditions) || options.delete("conditions") || {}
if conditions
case conditions
when Hash
conditions.each { |condition, value| search.conditions.send("#{condition}=", value) } # explicitly call to enforce blanks
else
search.conditions = conditions
end
end
search.options = options search.options = options
search.sanitize search.sanitize
end end
Expand Down Expand Up @@ -181,8 +184,12 @@ class << self
alias_method :new_search!, :build_search! alias_method :new_search!, :build_search!


def valid_find_options def valid_find_options
VALID_FIND_OPTIONS VALID_FIND_OPTIONS
end end

def valid_calculations_options
Calculations::CALCULATIONS_OPTIONS
end
end end
end end
end end
Expand Up @@ -135,7 +135,10 @@ def conditions=(conditions)
case conditions case conditions
when Hash when Hash
assert_valid_conditions(conditions) assert_valid_conditions(conditions)
remove_conditions_from_protected_assignement(conditions).each { |condition, value| send("#{condition}=", value) } remove_conditions_from_protected_assignement(conditions).each do |condition, value|
next if value.blank? # ignore blanks on mass assignments
send("#{condition}=", value)
end
else else
self.sql = conditions self.sql = conditions
end end
Expand Down
Expand Up @@ -92,12 +92,12 @@ def page_links_outer_spread=(value)
end end


def page_links_next # :nodoc: def page_links_next # :nodoc:
@page_links_next ||= "< Next" @page_links_next ||= "Next >"
end end


# The default for the :next option for the page_links helper. # The default for the :next option for the page_links helper.
# #
# * <tt>Default:</tt> "< Next" # * <tt>Default:</tt> "Next >"
# * <tt>Accepts:</tt> Anything you want, text, html, etc. nil to disable # * <tt>Accepts:</tt> Anything you want, text, html, etc. nil to disable
def page_links_next=(value) def page_links_next=(value)
@page_links_next = value @page_links_next = value
Expand All @@ -116,14 +116,14 @@ def page_links_prev=(value)
end end


def per_page # :nodoc: def per_page # :nodoc:
@per_page @per_page ||= per_page_choices[2]
end end


# The default for per page. This is only applicaple for protected searches. Meaning you start the search with new_search or new_conditions. # The default for per page. This is only applicaple for protected searches. Meaning you start the search with new_search or new_conditions.
# The reason for this not to disturb regular queries such as Whatever.find(:all). You would not expect that to be limited. # The reason for this not to disturb regular queries such as Whatever.find(:all). You would not expect that to be limited.
# #
# * <tt>Default:</tt> nil, nil means "show all" # * <tt>Default:</tt> The 3rd option in your per_page_choices, default of 50
# * <tt>Accepts:</tt> Any value in your per_page choices # * <tt>Accepts:</tt> Any value in your per_page choices, nil means "show all"
def per_page=(value) def per_page=(value)
@per_page = value @per_page = value
end end
Expand Down
Expand Up @@ -9,13 +9,21 @@ class Base
include Searchgasm::Shared::Searching include Searchgasm::Shared::Searching
include Searchgasm::Shared::VirtualClasses include Searchgasm::Shared::VirtualClasses


# Options ActiveRecord allows when searching
AR_FIND_OPTIONS = ::ActiveRecord::Base.valid_find_options

# Options ActiveRecord allows when performing calculations
AR_CALCULATIONS_OPTIONS = ::ActiveRecord::Base.valid_calculations_options

AR_OPTIONS = (AR_FIND_OPTIONS + AR_CALCULATIONS_OPTIONS).uniq

# Options that ActiveRecord doesn't suppport, but Searchgasm does # Options that ActiveRecord doesn't suppport, but Searchgasm does
SPECIAL_FIND_OPTIONS = [:order_by, :order_as, :page, :per_page] SPECIAL_FIND_OPTIONS = [:order_by, :order_as, :page, :per_page]


# Valid options you can use when searching # Valid options you can use when searching
VALID_FIND_OPTIONS = SPECIAL_FIND_OPTIONS + ::ActiveRecord::Base.valid_find_options # the order is very important, these options get set in this order OPTIONS = SPECIAL_FIND_OPTIONS + AR_OPTIONS # the order is very important, these options get set in this order


attr_accessor *::ActiveRecord::Base.valid_find_options attr_accessor *AR_OPTIONS


class << self class << self
# Used in the ActiveRecord methods to determine if Searchgasm should get involved or not. # Used in the ActiveRecord methods to determine if Searchgasm should get involved or not.
Expand Down Expand Up @@ -47,7 +55,7 @@ def acting_as_filter?
# Makes using searchgasm in the console less annoying and keeps the output meaningful and useful # Makes using searchgasm in the console less annoying and keeps the output meaningful and useful
def inspect def inspect
current_find_options = {} current_find_options = {}
::ActiveRecord::Base.valid_find_options.each do |option| AR_OPTIONS.each do |option|
value = send(option) value = send(option)
next if value.nil? next if value.nil?
current_find_options[option] = value current_find_options[option] = value
Expand All @@ -72,10 +80,9 @@ def offset=(value)


def options=(values) def options=(values)
return unless values.is_a?(Hash) return unless values.is_a?(Hash)
values.symbolize_keys.fast_assert_valid_keys(VALID_FIND_OPTIONS) values.symbolize_keys.fast_assert_valid_keys(OPTIONS)


# Do the special options first, and then the core options last, since the core options take precendence OPTIONS.each do |option|
VALID_FIND_OPTIONS.each do |option|
next unless values.has_key?(option) next unless values.has_key?(option)
send("#{option}=", values[option]) send("#{option}=", values[option])
end end
Expand All @@ -84,9 +91,9 @@ def options=(values)
end end


# Sanitizes everything down into options ActiveRecord::Base.find can understand # Sanitizes everything down into options ActiveRecord::Base.find can understand
def sanitize def sanitize(searching = true)
find_options = {} find_options = {}
::ActiveRecord::Base.valid_find_options.each do |find_option| (searching ? AR_FIND_OPTIONS : AR_CALCULATIONS_OPTIONS).each do |find_option|
value = send(find_option) value = send(find_option)
next if value.blank? next if value.blank?
find_options[find_option] = value find_options[find_option] = value
Expand Down
Expand Up @@ -51,8 +51,8 @@ def include_with_conditions
includes.blank? ? nil : (includes.size == 1 ? includes.first : includes) includes.blank? ? nil : (includes.size == 1 ? includes.first : includes)
end end


def sanitize_with_conditions # :nodoc: def sanitize_with_conditions(searching = true) # :nodoc:
find_options = sanitize_without_conditions find_options = sanitize_without_conditions(searching)
if conditions_obj = find_options.delete(:conditions) if conditions_obj = find_options.delete(:conditions)
new_conditions = conditions_obj.sanitize new_conditions = conditions_obj.sanitize
find_options[:conditions] = new_conditions unless new_conditions.blank? find_options[:conditions] = new_conditions unless new_conditions.blank?
Expand Down
Expand Up @@ -115,18 +115,20 @@ def order_by_includes


private private
def order_by_to_order(order_by, order_as, alt_klass = nil, new_includes = []) def order_by_to_order(order_by, order_as, alt_klass = nil, new_includes = [])
table_name = (alt_klass || klass).table_name k = alt_klass || klass
table_name = k.table_name
sql_parts = [] sql_parts = []


case order_by case order_by
when Array when Array
order_by.each { |part| sql_parts << order_by_to_order(part, order_as) } order_by.each { |part| sql_parts << order_by_to_order(part, order_as) }
when Hash when Hash
raise(ArgumentError, "when passing a hash to order_by you must only have 1 key: {:user_group => :name} not {:user_group => :name, :user_group => :id}. The latter should be [{:user_group => :name}, {:user_group => :id}]") if order_by.keys.size != 1 raise(ArgumentError, "when passing a hash to order_by you must only have 1 key: {:user_group => :name} not {:user_group => :name, :user_group => :id}. The latter should be [{:user_group => :name}, {:user_group => :id}]") if order_by.keys.size != 1
k = order_by.keys.first key = order_by.keys.first
v = order_by.values.first reflection = k.reflect_on_association(key.to_sym)
new_includes << k.to_sym value = order_by.values.first
sql_parts << order_by_to_order(v, order_as, eval(k.to_s.classify), new_includes) # using eval, better performance, protection makes sure nothing fishy goes on here new_includes << key.to_sym
sql_parts << order_by_to_order(value, order_as, reflection.klass, new_includes) # using eval, better performance, protection makes sure nothing fishy goes on here
when Symbol, String when Symbol, String
new_include = build_order_by_includes(new_includes) new_include = build_order_by_includes(new_includes)
self.order_by_includes << new_include if new_include self.order_by_includes << new_include if new_include
Expand Down
Expand Up @@ -24,8 +24,12 @@ module Protection
# Options that are allowed when protecting against SQL injections (still checked though) # Options that are allowed when protecting against SQL injections (still checked though)
SAFE_OPTIONS = Base::SPECIAL_FIND_OPTIONS + [:conditions, :limit, :offset] SAFE_OPTIONS = Base::SPECIAL_FIND_OPTIONS + [:conditions, :limit, :offset]


VULNERABLE_FIND_OPTIONS = Base::AR_FIND_OPTIONS - SAFE_OPTIONS

VULNERABLE_CALCULATIONS_OPTIONS = Base::AR_CALCULATIONS_OPTIONS - SAFE_OPTIONS

# Options that are not allowed, at all, when protecting against SQL injections # Options that are not allowed, at all, when protecting against SQL injections
VULNERABLE_OPTIONS = Base::VALID_FIND_OPTIONS - SAFE_OPTIONS VULNERABLE_OPTIONS = Base::OPTIONS - SAFE_OPTIONS


def self.included(klass) def self.included(klass)
klass.class_eval do klass.class_eval do
Expand Down Expand Up @@ -59,12 +63,13 @@ def order_by_safe?(order_by, alt_klass = nil)


k = alt_klass || klass k = alt_klass || klass
column_names = k.column_names column_names = k.column_names

[order_by].flatten.each do |column| [order_by].flatten.each do |column|
case column case column
when Hash when Hash
return false unless k.reflect_on_association(column.keys.first.to_sym) reflection = k.reflect_on_association(column.keys.first.to_sym)
return false unless order_by_safe?(column.values.first, column.keys.first.to_s.classify.constantize) return false unless reflection
return false unless order_by_safe?(column.values.first, reflection.klass)
when Array when Array
return false unless order_by_safe?(column) return false unless order_by_safe?(column)
else else
Expand Down
Expand Up @@ -21,17 +21,15 @@ def #{method}(*args)
end end
end_eval end_eval
end end

# Setup methods for calculating # Setup methods for calculating
CALCULATION_METHODS.each do |method| CALCULATION_METHODS.each do |method|
class_eval <<-"end_eval", __FILE__, __LINE__ class_eval <<-"end_eval", __FILE__, __LINE__
def #{method}(*args) def #{method}(*args)
options = args.extract_options! options = args.extract_options!
klass.send(:with_scope, :find => options) do klass.send(:with_scope, :find => options) do
find_options = (self.class < Searchgasm::Conditions::Base ? {:conditions => sanitize} : sanitize) find_options = (self.class < Searchgasm::Conditions::Base ? {:conditions => sanitize} : sanitize(false))
find_options.delete(:select) [:select, :limit, :offset].each { |option| find_options.delete(option) }
find_options.delete(:limit)
find_options.delete(:offset)
args << find_options args << find_options
klass.#{method}(*args) klass.#{method}(*args)
end end
Expand Down
Expand Up @@ -67,7 +67,7 @@ def to_a


MAJOR = 1 MAJOR = 1
MINOR = 1 MINOR = 1
TINY = 0 TINY = 1


# The current version as a Version instance # The current version as a Version instance
CURRENT = new(MAJOR, MINOR, TINY) CURRENT = new(MAJOR, MINOR, TINY)
Expand Down
@@ -1,18 +1,18 @@


# Gem::Specification for Searchgasm-1.1.0 # Gem::Specification for Searchgasm-1.1.1
# Originally generated by Echoe # Originally generated by Echoe


--- !ruby/object:Gem::Specification --- !ruby/object:Gem::Specification
name: searchgasm name: searchgasm
version: !ruby/object:Gem::Version version: !ruby/object:Gem::Version
version: 1.1.0 version: 1.1.1
platform: ruby platform: ruby
authors: authors:
- Ben Johnson of Binary Logic - Ben Johnson of Binary Logic
autorequire: autorequire:
bindir: bin bindir: bin


date: 2008-09-18 00:00:00 -04:00 date: 2008-09-19 00:00:00 -04:00
default_executable: default_executable:
dependencies: dependencies:
- !ruby/object:Gem::Dependency - !ruby/object:Gem::Dependency
Expand Down
Expand Up @@ -28,8 +28,9 @@ def test_standard_searches
assert_nothing_raised { Account.sum("id", {}) } assert_nothing_raised { Account.sum("id", {}) }
end end


def test_valid_find_options def test_ar_options
assert_equal [ :conditions, :include, :joins, :limit, :offset, :order, :select, :readonly, :group, :from, :lock ], ActiveRecord::Base.valid_find_options assert_equal [ :conditions, :include, :joins, :limit, :offset, :order, :select, :readonly, :group, :from, :lock ], ActiveRecord::Base.valid_find_options
assert_equal [:conditions, :joins, :order, :select, :group, :having, :distinct, :limit, :offset, :include, :from], ActiveRecord::Base.valid_calculations_options
end end


def test_build_search def test_build_search
Expand Down
Expand Up @@ -185,4 +185,13 @@ def test_any
conditions.any = false conditions.any = false
assert_equal [Account.find(1)], conditions.all assert_equal [Account.find(1)], conditions.all
end end

def test_ignoring_blanks
conditions = Account.new_conditions(:name => "", :created_after => nil)
assert_equal({}, conditions.conditions)
conditions.name = ""
assert_equal({:name_equals => ""}, conditions.conditions)
conditions.created_after = ""
assert_equal({:name_equals => ""}, conditions.conditions)
end
end end
Expand Up @@ -20,5 +20,8 @@ def test_protection


assert_raise(ArgumentError) { account.users.build_conditions("(DELETE FROM users)") } assert_raise(ArgumentError) { account.users.build_conditions("(DELETE FROM users)") }
assert_nothing_raised { account.users.build_conditions!("(DELETE FROM users)") } assert_nothing_raised { account.users.build_conditions!("(DELETE FROM users)") }

#search = Account.new_search
#assert_nothing_raised { search.conditions = "(DELETE FROM users)" }
end end
end end
Expand Up @@ -9,6 +9,7 @@
ActiveRecord::Base.establish_connection(:adapter => "sqlite3", :dbfile => ":memory:") ActiveRecord::Base.establish_connection(:adapter => "sqlite3", :dbfile => ":memory:")


class Account < ActiveRecord::Base class Account < ActiveRecord::Base
has_one :admin, :class_name => "User", :conditions => {:first_name => "Ben"}
has_many :users, :dependent => :destroy has_many :users, :dependent => :destroy
has_many :orders, :through => :users has_many :orders, :through => :users
end end
Expand All @@ -17,6 +18,7 @@ class User < ActiveRecord::Base
acts_as_tree acts_as_tree
belongs_to :account belongs_to :account
has_many :orders, :dependent => :destroy has_many :orders, :dependent => :destroy
has_one :cool_order, :class_name => "Order", :conditions => {:total => 100}
end end


class Order < ActiveRecord::Base class Order < ActiveRecord::Base
Expand Down

0 comments on commit f8e95aa

Please sign in to comment.