Skip to content

Instantly share code, notes, and snippets.

@avit
Last active December 10, 2015 01:38
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save avit/4360244 to your computer and use it in GitHub Desktop.
Save avit/4360244 to your computer and use it in GitHub Desktop.
Stupid ruby tricks for ActiveRecord query syntax. For amusement only.
module BacktickAttributeSyntax
extend self
# WARNING: this is a dangerous hack. Don't use it. It'll bite you if you ever
# accidentally call backticks outside of a model.
# Override backtick syntax to return an Arel attribute for use with
# predications like `.gteq` in the model. To use the original shell
# behaviour, (which should be very uncommon in ActiveRecord models), you can
# pass a string starting with a "!"
#
# where(`score`.gt 9000)
# where(`title`.like '% on rails')
#
# `!whoami`
#
def `(str)
if str[0] == ?!
shell_command = str[1..-1].to_sym
super(shell_command)
else
arel_table[str.to_sym]
end
end
end
# Don't do it, I warned you.
ActiveRecord::Base.extend BacktickAttributeSyntax
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment