Skip to content

Instantly share code, notes, and snippets.

@mschuerig
Created June 8, 2012 06:46
Show Gist options
  • Save mschuerig/2894031 to your computer and use it in GitHub Desktop.
Save mschuerig/2894031 to your computer and use it in GitHub Desktop.
Tools for the Rails console
if Rails.env.development? || Rails.env.test?
module ConsoleTools
EDITOR = ENV['CONSOLE_TOOLS_EDITOR'] || 'kwrite'
BROWSER = ENV['CONSOLE_TOOLS_BROWSER'] || 'firefox -new-window'
def edit_object(obj = @response)
# TODO add support for XML nodes
case obj
#when ActiveRecord::Base
# format = :yaml
# external = obj.attributes.to_yaml
when String
format = :string
external = obj
else
format = :yaml
external = obj.to_yaml
end
changed = nil
Tempfile.open('edit-object') do |f|
f.puts(external)
f.close
system "#{EDITOR} '#{f.path}' 2> /dev/null"
case format
when :yaml
changed = YAML.load_file(f.path)
when :string
changed = File.read(f.path)
end
end
if changed != external
case
#when obj.kind_of?(ActiveRecord::Base)
# obj.assign_attributes(changed, :without_protection => true)
# nil
when obj.respond_to?(:replace)
obj.replace(changed)
nil
else
changed
end
end
end
alias eee edit_object
def browse_object(obj = @response)
if obj.respond_to?(:body)
doc = obj.body
else
doc = obj.to_s
end
Tempfile.open('edit-object') do |f|
f.puts doc
f.close
system "#{BROWSER} '#{f.path}'"
end
nil
end
alias fff browse_object
def show_image(input)
IO.popen('display', 'wb') do |pipe|
pipe.write(input)
end
end
def pt_visual_explain(query)
case query
when ActiveRecord::Relation
ex = query.explain
when /^SELECT /
ex = ActiveRecord::Base.connection.explain(query)
when /^\+-/
ex = query
else
$stderr.puts "Can't handle this kind of input."
return
end
IO.popen('pt-visual-explain', 'w') do |pipe|
pipe.write(ex)
end
nil
end
alias qex pt_visual_explain
end
include ConsoleTools
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment