有没有一个简单的方法来漂亮打印(rails 3)控制台中的随机sql?
类似于awesome_print,甚至可能是Pretty Print.
它不必理解所有可能的方言或超先进.
我真正想要的是检查ActiveRecord生成的sql更容易.
目前我只是复制sql去在线格式化,这显然是一个生产力杀手.
我真的想要query.to_sql.pretty_format_sql并看到更好的输出.
谢谢.
解决方法
尝试这个:
git clone https://github.com/sonota/anbt-sql-formatter cd anbt-sql-formatter rails setup.rb
然后,在Rails初始化程序中:
# config/initializers/pretty_format_sql.rb class String def pretty_format_sql require "anbt-sql-formatter/formatter" rule = Anbtsql::Rule.new rule.keyword = Anbtsql::Rule::KEYWORD_UPPER_CASE %w(count sum substr date).each{|func_name| rule.function_names << func_name.upcase } rule.indent_string = " " formatter = Anbtsql::Formatter.new(rule) formatter.format(self) end end
测试:
rails console # Some complex sql puts Recipe.joins(:festivity).where(['? BETWEEN festivities.starts_at AND festivities.ends_at',Time.utc(0,Time.now.month,Time.now.day,12,0)]).to_sql.pretty_format_sql SELECT "recipes" . * FROM "recipes" INNER JOIN "festivities" ON "festivities" . "id" = "recipes" . "festivity_id" WHERE ( '0000-04-27 12:00:00.000000' BETWEEN festivities.starts_at AND festivities.ends_at ) => nil
我离开炼油(重构:猴子补丁 – >模块,自定义格式化等):-))