Skip to content

Instantly share code, notes, and snippets.

@unicornrainbow
Forked from zoras/.railsrc
Last active December 22, 2015 04:09
Show Gist options
  • Save unicornrainbow/6415399 to your computer and use it in GitHub Desktop.
Save unicornrainbow/6415399 to your computer and use it in GitHub Desktop.
.railsrc
# .railsrc for Rails 3, encoding: utf-8
# see http://rbjl.net/49-railsrc-rails-console-snippets
if !Rails.application then warn "Rails isn't loaded, yet... skipping .railsrc" else
# # #
def ripl?; defined?(Ripl) && Ripl.instance_variable_get(:@shell); end
# # #
# loggers
ActiveRecord::Base.logger = Logger.new STDOUT
ActiveRecord::Base.clear_reloadable_connections!
ActionController::Base.logger = Logger.new STDOUT
# # #
# named routes and helpers
include Rails.application.routes.url_helpers
default_url_options[:host] = Rails.application.class.parent_name.downcase
#include ActionView::Helpers # All Rails helpers
include ApplicationController._helpers # Your own helpers
#
# unfortunately that breaks some functionality (e.g. the named route helpers above)
# so, look at actionpack/lib/action_view/helpers.rb and choose the helpers you need
# (and which don't break anything), e.g.
include ActionView::Helpers::DebugHelper
include ActionView::Helpers::NumberHelper
include ActionView::Helpers::RawOutputHelper
include ActionView::Helpers::SanitizeHelper
include ActionView::Helpers::TagHelper
include ActionView::Helpers::TextHelper
include ActionView::Helpers::TranslationHelper
# # #
# route list view helpers (requires hirb)
# hirb view for a route
class Hirb::Helpers::Route < Hirb::Helpers::AutoTable
def self.render(output, options = {})
super( output.requirements.map{ |k,v|
[k, v.inspect]
}, options.merge({
:headers => [output.name || '', "#{ output.verb || 'ANY' } #{ output.path }"],
:unicode => true,
:description => nil,
}) )
end
end
Hirb.add_view ActionDispatch::Routing::Route, :class => Hirb::Helpers::Route
# short and long route list
def routes(long_output = false)
if long_output
Rails.application.routes.routes.each{ |e|
puts Hirb::Helpers::Route.render(e)
}
true
else
Hirb::Console.render_output Rails.application.routes.routes.map{|e|
[e.name || '', e.verb || 'ANY', e.path]
},{
:class => Hirb::Helpers::AutoTable,
:headers => %w<name verb path>,
}
end
end
# get a specific route via index or name
def route(index_or_name)
route = case index_or_name
when Integer
Rails.application.routes.routes[ index_or_name ]
when Symbol # named route
Rails.application.routes.named_routes.get index_or_name
end
end
# access to routeset for easy recognize / generate
def r
ActionController::Routing::Routes
end
# # #
# rails prompt
if ripl?
module Ripl::RailsPrompt
def prompt
@prompt = "#{ Rails.application.class.parent_name.downcase }(#{ Rails.env[0...3] })> "
super
end
end
Ripl::Shell.include Ripl::RailsPrompt
else
app_name = Rails.application.class.parent_name.downcase
app_env = Rails.env[0...3]
IRB.conf[:PROMPT] ||= {}
IRB.conf[:PROMPT][:RAILS] = {
:PROMPT_I => "#{ app_name }(#{ app_env })> ",
:PROMPT_N => "#{ app_name }(#{ app_env })| ",
:PROMPT_C => "#{ app_name }(#{ app_env })| ",
:PROMPT_S => "#{ app_name }(#{ app_env })%l ",
:RETURN => "=> %s\n",
:AUTO_INDENT => true,
}
IRB.conf[:PROMPT_MODE] = :RAILS
end
# # #
# per project histories
history_file = File.join Dir.pwd, '.console_history'
if ripl?
Ripl.config[:history] = history_file
else
if !IRB.conf[:PROMPT][:RVM]
IRB.conf[:HISTORY_FILE] = history_file
else # RVM workaround, code from ~/.rvm/scripts/irbrc.rb
# NOTE: messes up your ~/.irb-history
# consider editing the rvm script directly
if File.exists?(history_file)
lines = IO.readlines(history_file).collect { |line| line.chomp }
Readline::HISTORY.clear
Readline::HISTORY.push(*lines)
end
Kernel::at_exit do
maxhistsize = IRB.conf[:SAVE_HISTORY] || 100
history_file = File.join Dir.pwd, ".console_history"
lines = Readline::HISTORY.to_a.reverse.uniq.reverse
lines = lines[-maxhistsize, maxhistsize] if lines.compact.length > maxhistsize
File::open(history_file, "w+") { |io| io.puts lines.join("\n") }
end
end
end
# # #
# plain sql
def sql(query)
ActiveRecord::Base.connection.select_all(query)
end
# # #
# instead of User.find(...) you can do user(...)
# without arguments it only returns the model class
# based on http://www.clarkware.com/blog/2007/09/03/console-shortcut
Dir.glob( File.join(Dir.pwd, *%w<app models ** *.rb>) ).map { |file_name|
table_name = File.basename(file_name).split('.')[0..-2].join
Object.instance_eval do
define_method(table_name) do |*args|
table_class = table_name.camelize.constantize
if args.empty?
table_class
else
table_class.send(:find, *args)
end
end
end
}
# # #
# edit records with vim, emacs...
# class Url
# can_console_update
# end
# Url.first.console_update
# see https://github.com/cldwalker/console_update
require 'console_update'
# ConsoleUpdate.editor = 'vim' # not necessary if env var $EDITOR is set
# # #
# misc db helpers (requires hirb)
module DatabaseHelpers
extend self
def tables
Hirb::Console.render_output ActiveRecord::Base.connection.tables.map{|e|[e]},{
:class => Hirb::Helpers::AutoTable,
:headers => %w<tables>,
}
true
end
def table(which)
Hirb::Console.render_output ActiveRecord::Base.connection.columns(which).map{ |e|
[e.name, e.type, e.sql_type, e.limit, e.default, e.scale, e.precision, e.primary, e.null]
},{
:class => Hirb::Helpers::AutoTable,
:headers => %w<name type sql_type limit default scale precision primary null>,
}
true
end
def counts
Hirb::Console.render_output ActiveRecord::Base.connection.tables.map{|e|
[e, ActiveRecord::Base.connection.select_value("SELECT COUNT(*) FROM #{e}")]
},{
:class => Hirb::Helpers::AutoTable,
:headers => %w<table count>,
}
true
end
# ...
end
def db; DatabaseHelpers; end
# # #
# gems & plugin initializers
# initiate authlogic session
if defined? Authlogic
Authlogic::Session::Base.controller =
Authlogic::ControllerAdapters::RailsAdapter.new(self)
end
# ...
# # #
# temp patches
# hirb vs irb vs ripl
=begin
class << Hirb::View
def enable_output_method
if defined?(Ripl) && Ripl.instance_variable_get(:@shell)
@output_method = true
require 'ripl/hirb'
elsif defined? IRB
@output_method = true
::IRB::Irb.class_eval do
alias_method :non_hirb_view_output, :output_value
def output_value #:nodoc:
Hirb::View.view_or_page_output(@context.last_value) || non_hirb_view_output
end
end
end
end
end
#Hirb::View.disable
#Hirb::View.enable
=end
# # #
end # if Rails.application
# # #
#
# J-_-L
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment