1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
|
require 'utility_belt'
# Tracing irb
# http://blog.bleything.net/2006/12/11/tracing-method-execution
def enable_trace( event_regex = /^(call|return)/, class_regex = /IRB|Wirble|RubyLex|RubyToken/ )
puts "Enabling method tracing with event regex #{event_regex.inspect} and class exclusion regex #{class_regex.inspect}"
set_trace_func Proc.new{|event, file, line, id, binding, classname|
printf "[%8s] %30s %30s (%s:%-2d)\n", event, id, classname, file, line if
event =~ event_regex and
classname.to_s !~ class_regex
}
return
end
def disable_trace
puts "Disabling method tracing"
set_trace_func nil
end
# ------------------------------------------------------------------
# Wirble - Colors in irb
# http://pablotron.org/software/wirble/
# load libraries
require 'rubygems'
require 'wirble'
# start wirble (with color)
Wirble.init
Wirble.colorize
# ------------------------------------------------------------------
# Tab Completion
# http://whytheluckystiff.net/clog/ruby/tabCompletionInIRb.html
require 'irb/completion'
# ------------------------------------------------------------------
# simple irb prompt
IRB.conf[:PROMPT_MODE] = :SIMPLE
# ------------------------------------------------------------------
# Accessing rails helpers in console
# http://errtheblog.com/posts/41-real-console-helpers
def Object.method_added(method)
return super(method) unless method == :helper
(class<<self;self;end).send(:remove_method, :method_added)
def helper(*helper_names)
returning $helper_proxy ||= Object.new do |helper|
helper_names.each { |h| helper.extend "#{h}_helper".classify.constantize }
end
end
helper.instance_variable_set("@controller", ActionController::Integration::Session.new)
def helper.method_missing(method, *args, &block)
@controller.send(method, *args, &block) if @controller && method.to_s =~ /_path$|_url$/
end
helper :application rescue nil
end if ENV['RAILS_ENV']
# ------------------------------------------------------------------
# Command History
# http://blog.nicksieger.com/articles/2006/04/23/tweaking-irb
module Readline
module History
LOG = "#{ENV['HOME']}/.irb-history"
def self.write_log(line)
File.open(LOG, 'ab') {|f| f << "#{line}
"}
end
def self.start_session_log
write_log("
# session start: #{Time.now}
")
at_exit { write_log("
# session stop: #{Time.now}
") }
end
end
alias :old_readline :readline
def readline(*args)
ln = old_readline(*args)
begin
History.write_log(ln)
rescue
end
ln
end
end
Readline::History.start_session_log
# ------------------------------------------------------------------
require 'irb/ext/save-history'
IRB.conf[:SAVE_HISTORY] = 10000
IRB.conf[:HISTORY_FILE] = "#{ENV['HOME']}/.irb-save-history"
#------------------------------------------------------------------
def ri arg
puts `ri #{arg}`
end
class Module
def ri(meth=nil)
if meth
if instance_methods(false).include? meth.to_s
puts `ri #{self}##{meth}`
else
super
end
else
puts `ri #{self}`
end
end
end
# ------------------------------------------------------------------
# http://woss.name/2006/07/12/using-the-shell-within-irb/
require 'shell'
# Override the command processor widget for inserting system commands so
# that it behaves more like path-processing: earlier commands take precedence.
require 'shell/command-processor'
module FixAddDelegateCommandToShell
def self.extended(obj)
class << obj
alias_method :add_delegate_command_to_shell_override, :add_delegate_command_to_shell unless method_defined?(:add_delegate_command_to_shell_override)
alias_method :add_delegate_command_to_shell, :add_delegate_command_to_shell_no_override
end
end
def add_delegate_command_to_shell_no_override(id)
id = id.intern if id.kind_of?(String)
name = id.id2name
if Shell.method_defined?(id) or Shell::Filter.method_defined?(id)
Shell.notify "warn: Not overriding existing definition of Shell##{name}."
else
add_delegate_command_to_shell_override(id)
end
end
end
Shell::CommandProcessor.extend(FixAddDelegateCommandToShell)
# Allow Shell system commands to take :symbols too, to save a little typing.
require 'shell/system-command'
class Shell
class SystemCommand
alias_method :initialize_orig, :initialize
def initialize(sh, command, *opts)
opts.collect! {|opt| opt.to_s }
initialize_orig sh, command, *opts
end
end
end
# Provide me with a shell inside IRB to save quitting and restarting, or
# finding that other terminal window.
def shell
unless $shell
Shell.install_system_commands '' # no prefix
$shell = Shell.new
end
$shell
end
#------------------------------------------------------------------
# it loads a rails project into irb, useful if you really should have run ./script/console
def self.load_rails(from="./")
require File.expand_path(File.join(from,"config/boot"))
require File.join(RAILS_ROOT, 'config', 'environment')
end
# ------------------------------------------------------------------
# Iterative development in irb
# http://po-ru.com/diary/iterative-development-in-irb
# To use it, just type:
# loop_execute('myfile.rb')
# in irb. Control-C will return control to the regular irb shell.
def loop_execute(file)
old_mtime = nil
loop do
# print("\e[sWaiting...")
sleep(0.2) while (mtime = File.stat(file).mtime) == old_mtime
# print("\e[u\e[K")
begin
r = eval(File.read(file))
puts("=> #{r.inspect}")
rescue IRB::Abort
puts("Abort")
return
rescue Exception => e
puts("#{e.class}: #{e.message}\n#{e.backtrace.join("\n")}")
end
old_mtime = mtime
end
end
# ------------------------------------------------------------------
class Object
# p30 the rails way
# set some environment variables, that are normally sent to
# the dispatcher.
# then fool the dispatcher into thinking it is getting a request.
#
# The following command will return the contents of the webpage request
#
# request( :controller => "pages", :action => 'show', :id => 'home')
#
def request(options = {})
method = options.delete(:method) || :get
options.reverse_merge!(:only_path => true)
ENV['REQUEST_URI'] = app.url_for(options)
ENV['REQUEST_METHOD'] = method.to_s
Dispatcher.dispatch
end
end
# ------------------------------------------------------------------
# pm object
# pm object, :more - shows all methods including base Object methods
# pm object, :more, /to/ - shows all methods filtered by regexp
# Coded by sebastian delmont
ANSI_BOLD = "\033[1m"
ANSI_RESET = "\033[0m"
ANSI_LGRAY = "\033[0;37m"
ANSI_GRAY = "\033[1;30m"
def pm(obj, *options) # Print methods
methods = obj.methods
methods -= Object.methods unless options.include? :more
filter = options.select {|opt| opt.kind_of? Regexp}.first
methods = methods.select {|name| name =~ filter} if filter
data = methods.sort.collect do |name|
method = obj.method(name)
if method.arity == 0
args = "()"
elsif method.arity > 0
n = method.arity
args = "(#{(1..n).collect {|i| "arg#{i}"}.join(", ")})"
elsif method.arity < 0
n = -method.arity
args = "(#{(1..n).collect {|i| "arg#{i}"}.join(", ")}, ...)"
end
klass = $1 if method.inspect =~ /Method: (.*?)#/
[name, args, klass]
end
max_name = data.collect {|item| item[0].size}.max
max_args = data.collect {|item| item[1].size}.max
data.each do |item|
print " #{ANSI_BOLD}#{item[0].rjust(max_name)}#{ANSI_RESET}"
print "#{ANSI_GRAY}#{item[1].ljust(max_args)}#{ANSI_RESET}"
print " #{ANSI_LGRAY}#{item[2]}#{ANSI_RESET}\n"
end
data.size
end
#------------------------------------------------------------------
# In honor of Labor Day, here's a hack that might save you some. I spend a lot of time in the Rails console, and most of that time I'm finding stuff. Typing find is so... laborious. But drop this in your ~/.irbrc file, and your work is made light.
# # Creates shortcut methods for finding models.
# def define_model_find_shortcuts
# model_files = Dir.glob("app/models/**/*.rb")
# table_names = model_files.map { |f| File.basename(f).split('.')[0..-2].join }
# table_names.each do |table_name|
# Object.instance_eval do
# define_method(table_name) do |*args|
# table_name.camelize.constantize.send(:find, *args)
# end
# end
# end
# end
# # Called when the irb session is ready, after
# # the Rails goodies used above have been loaded.
# IRB.conf[:IRB_RC] = Proc.new { define_model_find_shortcuts }
|
Leave a Reply