Re-factoring common sql


#1

I would like to Not Repeat Myself ™ and re-factor frequently-used
SQL into some kind of attribute. For example, instead of re-writing
the “visible” conditions each time:

def find_by_name(name)
User.find(:first, :conditions=>[“visible = true and name = ?”,
name])
end

def find_by_login(login)
User.find(:first, :conditions=>[“visible=true and login=?”,
login])
end

I would like to instead skip the visible SQL each time and do
something like this:

User.visible.find(:first, :conditions=>[“name = ?”, name])
User.visible.find(:first, :conditions=>[“login=?”, login])

This is a contrived example I just made up, but is this possible?

thanks,
Jeff


#2

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Jeff,

What about defining another method that tacked on “visible = true”

def find_visible(*args)
args[:conditions] << " AND visible = true"
User.find args
end

def find_by_name(name)
User.find_visible :first, :conditions => [“name = ?”, name]
end

That answer feels weak, but maybe it’ll get you headed in the right
direction.

  • –Jeff

On Nov 20, 2005, at 10:46 AM, Jeff C. wrote:

 User.find(:first, :conditions=>["visible=true and login=?",  

thanks,
Jeff


Rails mailing list
removed_email_address@domain.invalid
http://lists.rubyonrails.org/mailman/listinfo/rails

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.1 (Darwin)

iD8DBQFDgM0IG9xIoXK+giARAheWAJ0U8DkMXMrkyLobbux5qs5cm0PbQwCfVyzr
sWY1lc4jYfpLEdqD1IyaGg8=
=BBbb
-----END PGP SIGNATURE-----


#3

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

oop!

Probably have to look more like

args[:conditions][0] << " AND visible = true"

On Nov 20, 2005, at 11:22 AM, Jeff S. wrote:

end
On Nov 20, 2005, at 10:46 AM, Jeff C. wrote:

def find_by_login(login)
This is a contrived example I just made up, but is this possible?

iD8DBQFDgM0IG9xIoXK+giARAheWAJ0U8DkMXMrkyLobbux5qs5cm0PbQwCfVyzr
sWY1lc4jYfpLEdqD1IyaGg8=
=BBbb
-----END PGP SIGNATURE-----


Rails mailing list
removed_email_address@domain.invalid
http://lists.rubyonrails.org/mailman/listinfo/rails

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.1 (Darwin)

iD8DBQFDgM2cG9xIoXK+giARAhShAKCeYEPXdNxEJyBHZmyHFUZei2x8TQCg2sa0
euB1y/r0MYsRHOVt5yx/h9w=
=JhYu
-----END PGP SIGNATURE-----