Skip to content

Instantly share code, notes, and snippets.

@chrisortman
Last active August 29, 2015 14:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrisortman/90916863b0812b7cdc32 to your computer and use it in GitHub Desktop.
Save chrisortman/90916863b0812b7cdc32 to your computer and use it in GitHub Desktop.
Converts finder methods to ActiveRecord 3
#!/usr/bin/env ruby -n
#
# You can setup shortcuts in vim that will run this automatically
#
# :map mm :.!~/<path_to_script>/fix_finders.rb<cr>
# Will replace the current line with the output of this script
#
# :map mn :t.<cr>:.!~/<path_to_script>/fix_finders.rb<cr>
# Will duplicate the line first so that you can do comparision of the
# changes.
#
# Quick refresher on some ruby special vars
# $_ is the current line from STDIN (happens because the -n on the bang at top of file)
# $` is the text before the regex match
# $' is the text after the regex match
# $1..$N is each numbered capture group from the regex. capture groups have unescaped parens around them
case $_
when /find\(:first,\s?:conditions => \[(.+)\],\s?:order => (["'].+["'])\)/
puts $` + %Q|where(#{$1}).order(#{$2}).first| + $'
when /find\(:first,\s?:order => (['"].+['"])\)/
puts $` + %Q|order(#{$1}).first| + $'
when /all\(:select => ["']DISTINCT (.+)["'],\s?:order => (['"].+['"]),\s?:conditions => ({.+})\)/
puts $` + %Q|all(#{$3}).order(#{$2}).select("#{$1}").distinct| + $'
when /all\(:select => (["'].+["']),\s?:order => (['"].+['"]),\s?:conditions => ({.+})\)/
puts $` + %Q|all(#{$3}).order(#{$2}).select(#{$1})| + $'
else
puts $_
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment