Creando consultas ActiveRecord a partir de SQL

Buscando la razón por la cual me falla un find_each dentro de un rake, me encontré con este sitio que sin dudas no deja de ser interesante. Suele pasar que tenemos en claro como construir una sentencia SQL pero no sabemos como hacerlo en ActiveRecord. Este pequeño script lo resuelve. Lo estuve probando y hay casos en los que no devuelve nada, como ser pasando rangos con BETWEEN, por ejemplo.


select * from members where first_name = 'Harold' and age = '34'
=> Members.find(:all, :conditions => {:age => "34", :first_name => "Harold"}

select * from members
=> Members.find(:all)

select * from members where first_name = 'Harold'
=> Members.find(:all, :conditions => {:first_name => "Harold"}

select * from members where first_name like '%Harold%'
=> Members.find(:all, :conditions => ["first_name like ?", '%Harold%'])

El script completo es este:


# converts a SQL statement to an ActiveRecord format
def sql_to_arf(sql)
table = sql[/from\s+(\w+)/,1]
remainder = $'

if remainder.length > 0 then
sql2 = remainder[/where\s+(.*);?/,1]

a1= sql2.split('and')
#puts a1.length if a1.length > 0

h = {}
a1.each do |condition|

b1 = condition.split('=')
if b1.length > 1 then
# is it a string or a number?; add to the hash
if b1[1].match(/'\w+'/) then
b1_val = b1[1].strip
val = b1[1][/'(\w+)'/,1]
h[b1[0].strip.to_sym] = val
else
h[b1[0].strip.to_sym] = b1[1].strip
end
format_conditions(table,h)
else
field, keyword = sql2.match(/(\w+)\s+like\s+(\'[^\']+\')/).captures
puts %Q(#{table.capitalize}.find(:all, :conditions => ["#{field} like ?", #{keyword}]))
end
end

else
puts "#{table.capitalize}.find(:all)"
end
end

def format_conditions(table, h)
conditions = []
h.each do |key,val|
fval = val.is_a?(String) ? %Q("#{val}") : val
condition = %Q(:#{key} => #{fval})
conditions << condition
end
puts "#{table.capitalize}.find(:all, :conditions => {#{conditions.join(', ')}}"
end

Fuente: DZone Snippets