[Rails] [ANN] Where Plugin

Ezra Zygmuntowicz ezra at yakimaherald.com
Mon Jan 2 00:15:22 GMT 2006


Jens-Christian-

	So I played with things a bit to make the Cond class take a block  
and make the find_with_conditions pass the block into the Cond.new  
statement. Here is the simplified code that if you made some changes  
to your Where class you could use the method_missing interface. Its  
using my Cond class instead of your Where class for now and a  
simplified version of the find_with_conditions just for examples sake:

class Cond

   def initialize(&block)
     @args = []
     instance_eval(&block) if block_given?
   end

   def method_missing(sym, *args)
       @args << [sym,args.flatten].flatten
   end

   def where(args=@args)
     args.each do |triplet|
       instance_variable_set("@#{triplet[0].to_sym}", triplet[2])
     end
     q = []
     ary = []
     args.each do |triplet|
       iv = instance_variable_get("@#{triplet[0]}")
       unless iv.nil? || iv.to_s == ''
           q << "#{triplet[0]} #{triplet[1]} ?"
           ary << iv
         end
     end
     return [q.join(" and ")].concat(ary)
   end
end

class Base
   def self.find_with_conditions(*args, &block)
     cond = Cond.new(&block)
    #code goes here for dealing with the options hash merge and  
calling find.
    # simplified for examples sake we will just return the where  
clause for now
     cond.where
   end
end

a = Base.find_with_conditions do
   month '<=', 11
   year '=' , "red"
end

p a
#=> ["month <= ? and year = ?", 11, "red"]

	So if you make your Where class use an initialize method that takes  
a block like my Cond class above does, then you can use the nice  
syntax with either find_with_conditions by passing the block into the  
constructor like this:  Cond.new(&block) or when you just want to  
build the where clause by itself like this:

c = Cond.new do
   month '<=', 11
   year '=', 2005
   name 'LIKE', 'ruby%'
end

c.where
# =>  ["month <= ? and year = ? and name LIKE ?", 11, 2005, "ruby%"]



	Play with that for a bit and see if you like it. I think it will be  
the easiest way to get the syntax we like. I will make this a patch  
for your where plugin later today unles you would rather do it? Let  
me know.

Cheers-

-Ezra Zygmuntowicz
WebMaster
Yakima Herald-Republic Newspaper
ezra at yakima-herald.com
509-577-7732

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://wrath.rubyonrails.org/pipermail/rails/attachments/20060102/175c0dc8/attachment.html


More information about the Rails mailing list