Created
June 22, 2009 18:49
-
-
Save ashgti/134117 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| #!ruby | |
| # Example OR and ALL finder | |
| # p a_model.all(:and => {:yes => true, | |
| # :conditions => 'yo'}, | |
| # :yo => 'no', | |
| # :or => {:yes => 'no', | |
| # :a => 'foo', | |
| # :bar => 'barz'}, | |
| # :limit => 5, | |
| # :order => :name) | |
| #=> SELECT * FROM MODEL WHERE (yes = 'true' AND conditions = 'yo') AND (a = 'foo' OR bar = 'barz' OR yes = 'no') AND (yo = 'no') ORDER BY name LIMIT 5 | |
| class Model | |
| def all args | |
| result = "SELECT * FROM MODEL WHERE" | |
| order = args.delete(:order) | |
| limit = args.delete(:limit) | |
| if and_options = args.delete(:and) | |
| result += " (" | |
| and_options.each do |k, v| | |
| result += "#{k.to_s} = '#{v.to_s}' AND " | |
| end | |
| result = "#{result[0, result.length - 5]})" | |
| end | |
| if or_options = args.delete(:or) | |
| result += " AND (" | |
| or_options.each do |k, v| | |
| result += "#{k.to_s} = '#{v.to_s}' OR " | |
| end | |
| result = "#{result[0, result.length - 4]})" | |
| end | |
| args.each do |k, v| | |
| result += " AND (#{k} = '#{v}')" | |
| end | |
| if order | |
| result += " ORDER BY #{order}" | |
| end | |
| if limit | |
| result += " LIMIT #{limit}" | |
| end | |
| result | |
| end | |
| end | |
| a_model = Model.new | |
| p a_model.all(:and => {:yes => true, | |
| :conditions => 'yo'}, | |
| :yo => 'no', | |
| :or => {:yes => 'no', | |
| :a => 'foo', | |
| :bar => 'barz'}, | |
| :limit => 5, | |
| :order => :name) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment