utility_belt 1.0.0

Sign up to get free protection for your applications and to get access to all the features.
data/History.txt ADDED
@@ -0,0 +1,5 @@
1
+ == 1.0.0 / 2007-11-03
2
+
3
+ * 1 major enhancement
4
+ * Birthday!
5
+
data/Manifest.txt ADDED
@@ -0,0 +1,7 @@
1
+ History.txt
2
+ Manifest.txt
3
+ README.txt
4
+ Rakefile
5
+ bin/utility_belt
6
+ lib/utility_belt.rb
7
+ test/test_utility_belt.rb
data/README ADDED
@@ -0,0 +1,343 @@
1
+ == Utility Belt
2
+
3
+ by Giles Bowkett (and many others)
4
+
5
+ http://utilitybelt.rubyforge.org
6
+
7
+ == DESCRIPTION
8
+
9
+ Utility Belt is a grab-bag of tricks, tools, techniques, trifles, and toys for IRB, including convenience methods, language patches, and useful extensions. It also includes a couple command-line widgets. Its primary inspirations were an awesome gem called Wirble and a blog post by Amy Hoy called "Secrets Of The Rails Console Ninjas".
10
+
11
+ (http://slash7.com/articles/2006/12/21/secrets-of-the-rails-console-ninjas)
12
+
13
+ == INSTALL
14
+
15
+ sudo gem install utility_belt
16
+
17
+ == FEATURES
18
+
19
+ * Interactively edit IRB code in your preferred text editor
20
+ * Read from and write to OS X clipboard
21
+ * Post your code to Pastie with one command (OS X only)
22
+ * Kick-ass Unix-style history buffer
23
+ * Write command history to file or vi
24
+ * Grep classes and methods for strings
25
+ * Verbosity controls for regular IRB and Rails console
26
+ * Finder shortcuts for Rails console
27
+ * Upload shortcut for Amazon S3
28
+ * Command-line Amazon S3 upload script
29
+ * Command-line Google shortcut (OS X only)
30
+ * Auto-indentation
31
+ * _ special variable (like Unix shell var !!)
32
+ * Extremely basic themes for Wirble syntax coloring
33
+ * Pascal/JavaScript-style "with" statement
34
+ * String#to_proc
35
+ * Grammatically-correct is_an? method - no more "is_a? Array" statements
36
+ * One-character exit command
37
+
38
+ == MAYBE GONNA HAPPEN
39
+
40
+ * Class and method greps to take regexes and symbols
41
+ * Gem require to take arrays and symbols
42
+ * Copy history to clipboard or arbitrary editor
43
+ * Verbosity off switch for Rails
44
+ * Test-driven strategy encompassing IRB and external editors
45
+
46
+ == COMMUNITY EFFORT
47
+
48
+ The majority of this code was written by other people and compiled, nicked, nabbed, herded, gathered, copied, or pilfered by me (Giles Bowkett). See copyright notice for the credits. A lot of this code comes from blogs. Check out the source code for numerous links to the original posts the code came from.
49
+
50
+ == SYNOPSIS
51
+
52
+ Utility Belt gives you a ton of new options and techniques in IRB. (You may find yourself putting its language patches in actual projects as well.) The way to use Utility Belt is to edit, or create, your .irbrc file. This is analogous to a Unix .bashrc, .tcshrc, .profile, or similar file.
53
+
54
+ (Windows users are probably out of luck here - sorry. There may be a solution, but I don't know what it is.)
55
+
56
+ Adding Utility Belt to your .irbrc is easy:
57
+
58
+ require 'rubygems'
59
+ require 'utility_belt'
60
+
61
+ To use the Amazon shortcuts, you also need to set some environment variables. See the section on S3 under "Usage" for more. Also, if your terminal has a light background, you'll need to enable the light-background syntax coloring theme - see the section on themes under "Usage" for more.
62
+
63
+ == USAGE
64
+
65
+ Using each of Utility Belt's tools is different:
66
+
67
+ == Interactively edit IRB code in your preferred text editor
68
+
69
+ If your preferred text editor is vi(m), emacs, or TextMate, there are built-in commands: vi, emacs, and mate, respectively. To use another editor, use this command:
70
+
71
+ edit(:the_name_of_my_editor)
72
+
73
+ or
74
+
75
+ edit("the name of my editor")
76
+
77
+ or
78
+
79
+ edit("/the/path/to/my/editor")
80
+
81
+ == Read from and write to OS X clipboard
82
+
83
+ To read:
84
+
85
+ MacClipboard.read
86
+
87
+ To write:
88
+
89
+ MacClipboard.write("something")
90
+
91
+ == Post your code to Pastie with one command (OS X only)
92
+
93
+ First copy some code into your clipboard, or put it there with the MacClipboard.write() class method. Then use the command:
94
+
95
+ pastie
96
+
97
+ or the shortcut version:
98
+
99
+ pst
100
+
101
+ Note that this method currently auto-formats all code as Ruby. Support for other languages is possible but not implemented yet. Also, this code is OS X only because it uses the MacClipboard. (A platform-agnostic version without the clipboard aspect is certainly possible.)
102
+
103
+ == Unix-style history buffer
104
+
105
+ Use "h" or "history" to view your command history, and "h! 123" to re-invoke command #123 in your buffer. "h!" with no args will run the last command.
106
+
107
+ == Write command history to file or vi
108
+
109
+ To write your history to a file, use "history_write('/path/to/file')". To edit your history in vi, use "history_to_vi" or its shortcut alias "hvi".
110
+
111
+ == Grep classes and methods for strings
112
+
113
+ Classes:
114
+
115
+ >> grep_classes("ixnum")
116
+ #=> ["Fixnum"]
117
+
118
+ >> grep_classes("num")
119
+ #=> ["Bignum", "Fixnum", "Numeric", "REXML::SyncEnumerator"]
120
+
121
+ Methods:
122
+
123
+ >> "any arbitrary string".grep_methods("pretty")
124
+ #=> ["pretty_inspect", "pretty_print_instance_variables", "pretty_print_inspect", "pretty_print", "pretty_print_cycle"]
125
+
126
+ >> 32.grep_methods("*")
127
+ #=> ["*", "**"]
128
+
129
+ At some point it'll probably be a good idea to add regex support for these methods.
130
+
131
+ == Verbosity controls for regular IRB and Rails console
132
+
133
+ regular IRB: "verbose" or "v" / "quiet" or "q"
134
+
135
+ Rails: "log" method turns verbosity on, there isn't actually any method for turning it off. (Might add one at some point.)
136
+
137
+ == Finder shortcuts for Rails console
138
+
139
+ user(:all) / user(1)
140
+
141
+ instead of
142
+
143
+ User.find(:all) / User.find(1)
144
+
145
+ Supports arbitrarily complex finds.
146
+
147
+ == Upload shortcut for Amazon S3
148
+
149
+ First, define your secret keys in your environment variables:
150
+
151
+ export AMAZON_ACCESS_KEY_ID='foofoofoofoofoo'
152
+ export AMAZON_SECRET_ACCESS_KEY='barbarbarbarbar'
153
+
154
+ (Obviously, replace those with actual values.)
155
+
156
+ Then, you can use
157
+
158
+ aws_upload("bucket_name","filename")
159
+
160
+ To easily upload public-access files. This method will automatically connect to Amazon S3 for you, if your keys are defined in your environment variables. It also writes the resulting Amazon URL to your clipboard, if you're on OS X, so you can easily share the file with others. Note that you have to create the initial buckets manually - see amazon.rubyforge.org for details on that.
161
+
162
+ A good way to use this is actually to have a default bucket, and create a further method in your .irbrc file:
163
+
164
+ def my_bucket_name(filename)
165
+ aws_upload("my_default_bucket",filename)
166
+ end
167
+
168
+ == Command-line Amazon S3 upload script
169
+
170
+ Utility Belt also includes amazon, a simple command-line uploader for S3. It requires that you set your Amazon environment variables (see above). The usage is:
171
+
172
+ amazon -b my_bucket_name filename other_filename
173
+
174
+ (For any arbitrary number of filenames.)
175
+
176
+ Anytime you want to upload a file to your default bucket on S3, for example, the "images" bucket for your blog - or the "mp3" bucket if you're running a blog like Projectionist - all you have to do is
177
+
178
+ amazon -b blog_files some_file.name
179
+
180
+ Or
181
+
182
+ amazon --bucket blog_files some_file.name
183
+
184
+ And you're good to go. Of course, if that were too many characters to type, you could always take it one step further with a shell script. For instance, in bash:
185
+
186
+ alias b1="amazon --bucket my_main_bucket $1"
187
+ alias b2="amazon --bucket my_other_bucket $1"
188
+
189
+ And then you would only have to type:
190
+
191
+ b1 file.name
192
+
193
+ And of course tab completion will handle all the typing of the file name, assuming you choose your file names deliberately ahead of time to make tab completion effective, in which case all you have to type is "b1 f[tab]" and bam.
194
+
195
+ == Command-line Google shortcut (OS X only)
196
+
197
+ To pop open a new window in your default browser with Google search results for a given search term, do:
198
+
199
+ google "any given term"
200
+
201
+ For one-word terms, you can omit the quotes:
202
+
203
+ google term
204
+
205
+ If you already have the search term in your clipboard, you can just type:
206
+
207
+ google
208
+
209
+ (The last approach is useful for unusual command-line error messages.)
210
+
211
+ == Auto-indentation and tab completion
212
+
213
+ Just type as normally. This just enables built-in but underused functionality in IRB. (The IRB default auto-indentation isn't perfect, but it clobbers the living hell out of no indentation at all.)
214
+
215
+ == _ special variable (like Unix shell var !!)
216
+
217
+ More activation of built-in but underused functionality in IRB. _ functions like !! in Unix, with one subtle difference. Instead of re-issuing the previous command in your history, it gives you the last result of evaluating a command. This means when you start a new IRB session, _ won't go to your history, it'll just give you nil, and it means that some commands can't be repeated exactly. Nine out of ten times, however, it's pretty much the same thing.
218
+
219
+ Note that when combined with the h! in the command history code, you basically have two synonyms for !! here. Neither one is an exact replica, but between the two of them, you should have what you need.
220
+
221
+ == Extremely basic themes for Wirble syntax coloring
222
+
223
+ Utility Belt incorporates Wirble as a dependency. Wirble provides syntax coloring. Utility Belt allows you to choose between two syntax coloring themes: Wirble's default, and an alternate color set for terminals with light backgrounds. The default theme is enabled by default (duh), but if you have a terminal with a light background, you can enable the light-background theme just by putting the following line of code in your .irbrc:
224
+
225
+ UtilityBelt::Themes.background(:light)
226
+
227
+ To revert back to the default, just use this:
228
+
229
+ UtilityBelt::Themes.background(:dark)
230
+
231
+ To specify an entirely new syntax color scheme, see the source code for this gem or for Wirble.
232
+
233
+ == Pascal/JavaScript-style "with" statement
234
+
235
+ I use this with RSpec's spec_helper. Instead of:
236
+
237
+ Spec::Runner.configure do |config|
238
+ config.use_transactional_fixtures = true
239
+ config.use_instantiated_fixtures = false
240
+ config.fixture_path = RAILS_ROOT + '/spec/fixtures'
241
+ config.mock_with :flexmock
242
+ end
243
+
244
+ I do this:
245
+
246
+ Spec::Runner.configure do |config|
247
+ with(config) do
248
+ use_transactional_fixtures = true
249
+ use_instantiated_fixtures = false
250
+ fixture_path = RAILS_ROOT + '/spec/fixtures'
251
+ mock_with :flexmock
252
+ end
253
+ end
254
+
255
+ Note however that this blew up once and I have no idea why. Caveat emptor, et cetera.
256
+
257
+ == String#to_proc
258
+
259
+ Syntactic sugar for functional programming.
260
+
261
+ (1..3).map(&'*2') => [2, 4, 6]
262
+ (1..3).map(&'[-1, _, 0]') => [[-1, 1, 0], [-1, 2, 0], [-1, 3, 0]]
263
+ (1..3).map(&'x -> y -> x * y').map(&'[2]') => [2, 4, 6]
264
+ (1..5).select(&'>2') => [3, 4, 5]
265
+ (1..3).map(&'x -> y -> x * y').map(&'.call(2)') => [2, 4, 6]
266
+ [5].map(&"(1.._).inject(&'*')") => [120]
267
+
268
+ For more detail see: http://weblog.raganwald.com/2007/10/stringtoproc.html
269
+
270
+ == Grammatically-correct is_an? method - no more "is_a? Array" statements
271
+
272
+ >> [].is_an? Array
273
+ #=> true
274
+
275
+ Most people don't care, but personally, "is_a? Array" drives me completely insane.
276
+
277
+ == Object#not
278
+
279
+ Replace this:
280
+
281
+ if !response.incomplete? && !response.invalid? && response.total > 0
282
+
283
+ With this:
284
+
285
+ if response.not.incomplete? && response.not.invalid? && response.total > 0
286
+
287
+ Syntactic sugar for boolean conditions.
288
+
289
+ More detail here:
290
+
291
+ http://blog.jayfields.com/2007/08/ruby-adding-not-method-for-readability.html
292
+
293
+ == One-character exit command
294
+
295
+ x
296
+
297
+ Because life is too short to type whole words.
298
+
299
+ == REQUIREMENTS
300
+
301
+ * ReadLine
302
+ * Wirble
303
+ * Amazon S3
304
+ * Platform
305
+ * Some features require OS X
306
+
307
+ == LICENSE
308
+
309
+ (The MIT License)
310
+
311
+ Copyright (c) 2006-2007 Giles Bowkett
312
+ Portions Copyright (c) 2006-2007 Ben Bleything
313
+ Portions Copyright (c) 2006-2007 Reginald Braithwaite
314
+ Portions Copyright (c) 2006-2007 Gregory Brown
315
+ Portions Copyright (c) 2006-2007 Jamis Buck
316
+ Portions Copyright (c) 2006-2007 Mike Clark
317
+ Portions Copyright (c) 2006-2007 Jay Fields
318
+ Portions Copyright (c) 2005 David Heinemeier Hansson
319
+ Portions Copyright (c) 2006-2007 Ara T. Howard
320
+ Portions Copyright (c) 2006-2007 Pat Maddox
321
+ Portions Copyright (c) 2006-2007 Marcel Molina, Jr.
322
+ Portions Copyright (c) 2006-2007 Rick D. Natale
323
+ Portions Copyright (c) 2006-2007 Projectionist (Marcel Molina? Chad Fowler?)
324
+ Portions Copyright (c) 2006-2007 Dan Yoder
325
+
326
+ Permission is hereby granted, free of charge, to any person obtaining
327
+ a copy of this software and associated documentation files (the
328
+ 'Software'), to deal in the Software without restriction, including
329
+ without limitation the rights to use, copy, modify, merge, publish,
330
+ distribute, sublicense, and/or sell copies of the Software, and to
331
+ permit persons to whom the Software is furnished to do so, subject to
332
+ the following conditions:
333
+
334
+ The above copyright notice and this permission notice shall be
335
+ included in all copies or substantial portions of the Software.
336
+
337
+ THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
338
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
339
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
340
+ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
341
+ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
342
+ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
343
+ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/Rakefile ADDED
@@ -0,0 +1,20 @@
1
+ # -*- ruby -*-
2
+
3
+ require 'rubygems'
4
+ require 'hoe'
5
+ require './lib/utility_belt.rb'
6
+
7
+ Hoe.new('UtilityBelt', UtilityBelt::VERSION) do |p|
8
+ p.rubyforge_name = 'utility_belt'
9
+ # p.author = 'Giles Bowkett'
10
+ # p.email = 'gilesb@gmail.com'
11
+ # p.summary = 'IRB funk'
12
+ # p.description = p.paragraphs_of('README.txt', 2..5).join("\n\n")
13
+ # p.url = p.paragraphs_of('README.txt', 0).first.split(/\n/)[1..-1]
14
+ p.changes = p.paragraphs_of('History.txt', 0..1).join("\n\n")
15
+ end
16
+
17
+ # vim: syntax=Ruby
18
+
19
+ # I used Hoe to create the dirs etc., but from then on did most of it manually.
20
+ # (I figure if you're reading this at all, the reason is curiousity.)
data/bin/amazon ADDED
@@ -0,0 +1,21 @@
1
+ #!/usr/bin/env ruby
2
+ %w{rubygems platform aws/s3 optparse}.each {|library| require library}
3
+
4
+ option_parser = OptionParser.new
5
+ option_parser.on("-b", "--bucket NAME", String) {|bucket| @bucket = bucket}
6
+ filenames = option_parser.parse(ARGV)
7
+
8
+ if @bucket && filenames
9
+ UTILITY_BELT_IRB_STARTUP_PROCS = {}
10
+
11
+ utility_belt_lib = File.dirname(__FILE__) + '/../lib'
12
+ require "#{utility_belt_lib}/mac_clipboard"
13
+ require "#{utility_belt_lib}/amazon_upload_shortcut"
14
+
15
+ UTILITY_BELT_IRB_STARTUP_PROCS[:define_s3_convenience_methods].call
16
+
17
+ filenames.each {|filename| puts aws_upload(@bucket, filename)}
18
+ else
19
+ puts "Usage: amazon -b bucket_name file_name"
20
+ exit
21
+ end
data/bin/google ADDED
@@ -0,0 +1,15 @@
1
+ #!/usr/bin/env ruby
2
+ %w{rubygems platform}.each {|library| require library}
3
+ require "#{File.dirname(__FILE__) + '/../lib'}/mac_clipboard"
4
+
5
+ if :macosx == Platform::IMPL
6
+ search_term = ARGV[0] || MacClipboard.read
7
+ if search_term.empty?
8
+ puts "Usage: google search_term_without_spaces"
9
+ puts " google 'search term with spaces'"
10
+ puts " google"
11
+ puts " (if invoking without command-line args, must have text in clipboard buffer)"
12
+ exit
13
+ end
14
+ system("open http://google.com/search?q=#{search_term.gsub(/ |\n/, '%20')}")
15
+ end
@@ -0,0 +1,12 @@
1
+ # S3 (http://amazon.rubyforge.org/)
2
+ UTILITY_BELT_IRB_STARTUP_PROCS[:define_s3_convenience_methods] = lambda do
3
+ require 'aws/s3'
4
+ def aws_upload(bucket,filename)
5
+ AWS::S3::Base.establish_connection!(:access_key_id => ENV['AMAZON_ACCESS_KEY_ID'],
6
+ :secret_access_key => ENV['AMAZON_SECRET_ACCESS_KEY'])
7
+ AWS::S3::S3Object.store(filename, open(filename), bucket, :access => :public_read)
8
+ url = "http://s3.amazonaws.com/#{bucket}/#{filename}".gsub(/ /, "%20")
9
+ MacClipboard.write(url) if :macosx == Platform::IMPL
10
+ url
11
+ end
12
+ end
@@ -0,0 +1,74 @@
1
+ # history
2
+ # http://blog.bleything.net/pages
3
+ # http://gilesbowkett.blogspot.com/2007/06/irbrc-modifications.html
4
+ # Ben's history stuff, slightly modified, plus hvi method
5
+ class Object
6
+ def history(how_many = 50)
7
+ history_size = Readline::HISTORY.size
8
+ # no lines, get out of here
9
+ puts "No history" and return if history_size == 0
10
+ start_index = 0
11
+ # not enough lines, only show what we have
12
+ if history_size <= how_many
13
+ how_many = history_size - 1
14
+ end_index = how_many
15
+ else
16
+ end_index = history_size - 1 # -1 to adjust for array offset
17
+ start_index = end_index - how_many
18
+ end
19
+ start_index.upto(end_index) {|i| print_line i}
20
+ end
21
+ alias :h :history
22
+
23
+ # -2 because -1 is ourself
24
+ def history_do(lines = (Readline::HISTORY.size - 2))
25
+ irb_eval lines
26
+ end
27
+ alias :h! :history_do
28
+
29
+ def history_write(filename, lines)
30
+ file = File.open(filename, 'w')
31
+ get_lines(lines).each do |l|
32
+ file << "#{l}\n"
33
+ end
34
+ file.close
35
+ end
36
+
37
+ # TODO: history_write should go to a file, or the clipboard, or a file which opens in an application
38
+ def history_to_vi
39
+ file = Tempfile.new("irb_tempfile")
40
+ get_lines(0..(Readline::HISTORY.size - 1)).each do |line|
41
+ file << "#{line}\n"
42
+ end
43
+ file.close
44
+ system("vim #{file.path}")
45
+ end
46
+ alias :hvi :history_to_vi
47
+
48
+ private
49
+ def get_line(line_number)
50
+ Readline::HISTORY[line_number]
51
+ end
52
+
53
+ def get_lines(lines = [])
54
+ return [get_line(lines)] if lines.is_a? Fixnum
55
+ out = []
56
+ lines = lines.to_a if lines.is_a? Range
57
+ lines.each do |l|
58
+ out << Readline::HISTORY[l]
59
+ end
60
+ out
61
+ end
62
+
63
+ def print_line(line_number, show_line_numbers = true)
64
+ print line_number.to_s + ": " if show_line_numbers
65
+ puts get_line(line_number)
66
+ end
67
+
68
+ def irb_eval(lines)
69
+ to_eval = get_lines(lines)
70
+ to_eval.each {|l| Readline::HISTORY << l}
71
+ eval to_eval.join("\n")
72
+ end
73
+ end
74
+
@@ -0,0 +1,42 @@
1
+ # Giles Bowkett, Greg Brown, and several audience members from Giles' Ruby East presentation.
2
+ class InteractiveEditor
3
+ attr_accessor :editor
4
+ def initialize(editor = :vim)
5
+ @editor = editor.to_s
6
+ if @editor == "mate"
7
+ @editor = "mate -w"
8
+ end
9
+ end
10
+ def edit
11
+ unless @file
12
+ @file = Tempfile.new("irb_tempfile")
13
+ end
14
+ system("#{@editor} #{@file.path}")
15
+ Object.class_eval(`cat #{@file.path}`)
16
+ rescue Exception => error
17
+ puts error
18
+ end
19
+ end
20
+
21
+ class Object
22
+ def edit(editor)
23
+ unless IRB.conf[:interactive_editors] && IRB.conf[:interactive_editors][editor]
24
+ IRB.conf[:interactive_editors] ||= {}
25
+ IRB.conf[:interactive_editors][editor] = InteractiveEditor.new(editor)
26
+ end
27
+ IRB.conf[:interactive_editors][editor].edit
28
+ end
29
+
30
+ def vi
31
+ edit(:vim)
32
+ end
33
+
34
+ def mate
35
+ edit(:mate)
36
+ end
37
+
38
+ def emacs
39
+ edit(:emacs)
40
+ end
41
+ end
42
+
@@ -0,0 +1,3 @@
1
+ # auto indent, _ special var
2
+ IRB.conf[:AUTO_INDENT] = true
3
+ IRB.conf[:EVAL_HISTORY] = 1000
@@ -0,0 +1,30 @@
1
+ # IRB verbosity: http://groups.google.com/group/ruby-talk-google/browse_thread/thread/9c1febbe05513dc0
2
+ module IRB
3
+ def self.result_format
4
+ conf[:PROMPT][conf[:PROMPT_MODE]][:RETURN]
5
+ end
6
+ def self.result_format=(str)
7
+ result_format.replace(str)
8
+ end
9
+ def self.show_results
10
+ self.result_format = "=> %s\n"
11
+ end
12
+ def self.hide_results
13
+ self.result_format = ''
14
+ end
15
+ end
16
+
17
+ class Object
18
+ def verbose
19
+ IRB.show_results
20
+ end
21
+ alias :v :verbose
22
+
23
+ def quiet
24
+ IRB.hide_results
25
+ end
26
+ alias :q :quiet
27
+
28
+ alias :x :exit
29
+ end
30
+
data/lib/is_an.rb ADDED
@@ -0,0 +1,4 @@
1
+ # is_a? Array bothers me
2
+ class Object
3
+ alias :is_an? :is_a?
4
+ end
@@ -0,0 +1,19 @@
1
+ # TODO: upgrade these to take either regexes or strings
2
+
3
+ # http://gilesbowkett.blogspot.com/2006/12/smalltalk-cleverness-translated-into.html
4
+ # http://gilesbowkett.com/blog_code_samples/122906_seaside_rails/controller.txt
5
+ class Object
6
+ def grep_classes(search_term)
7
+ classes = []
8
+ ObjectSpace.each_object {|object| classes << object.name if object.is_a? Class and not object.name.blank?}
9
+ classes.find_all {|klass| klass.downcase.include? search_term.downcase}
10
+ end
11
+ end
12
+
13
+ # http://gilesbowkett.blogspot.com/2007/11/irb-what-was-that-method-again.html
14
+ class Object
15
+ def grep_methods(search_term)
16
+ methods.find_all {|method| method.downcase.include? search_term.downcase}
17
+ end
18
+ end
19
+
@@ -0,0 +1,15 @@
1
+ # original clipboard code: http://project.ioni.st/post/1334#snippet_1334
2
+ # turned it into a class to make it flexxy:
3
+ # http://gilesbowkett.blogspot.com/2007/09/improved-auto-pastie-irb-code.html
4
+ class MacClipboard
5
+ if :macosx == Platform::IMPL
6
+ class << self
7
+ def read
8
+ IO.popen('pbpaste') {|clipboard| clipboard.read}
9
+ end
10
+ def write(stuff)
11
+ IO.popen('pbcopy', 'w+') {|clipboard| clipboard.write(stuff)}
12
+ end
13
+ end
14
+ end
15
+ end
data/lib/not.rb ADDED
@@ -0,0 +1,15 @@
1
+ # http://blog.jayfields.com/2007/08/ruby-adding-not-method-for-readability.html
2
+ class Object
3
+ define_method :not do
4
+ Not.new(self)
5
+ end
6
+ class Not
7
+ private *instance_methods.select { |m| m !~ /(^__|^\W|^binding$)/ }
8
+ def initialize(subject)
9
+ @subject = subject
10
+ end
11
+ def method_missing(sym, *args, &blk)
12
+ !@subject.send(sym,*args,&blk)
13
+ end
14
+ end
15
+ end
data/lib/pastie.rb ADDED
@@ -0,0 +1,16 @@
1
+ # automate creating pasties
2
+ class Object
3
+ if :macosx == Platform::IMPL
4
+ def pastie
5
+ url =
6
+ pastie_url = Net::HTTP.post_form(URI.parse("http://pastie.caboo.se/pastes/create"),
7
+ {"paste_parser" => "ruby",
8
+ "paste[authorization]" => "burger",
9
+ "paste[body]" => MacClipboard.read}).body.match(/href="([^\"]+)"/)[1]
10
+ MacClipboard.write(pastie_url)
11
+ system("open #{pastie_url}")
12
+ pastie_url
13
+ end
14
+ alias :pst :pastie
15
+ end
16
+ end
@@ -0,0 +1,18 @@
1
+ # http://www.clarkware.com/cgi/blosxom/2007/09/03#ConsoleFindShortcut
2
+ # Mike Clark's find() shortcut for Rails console
3
+
4
+ # Creates shortcut methods for finding models.
5
+ UTILITY_BELT_IRB_STARTUP_PROCS[:define_model_find_shortcuts] = lambda do
6
+ if defined? ActiveRecord::Base || defined? ActiveResource::Base
7
+ model_files = Dir.glob("app/models/**/*.rb")
8
+ table_names = model_files.map { |f| File.basename(f).split('.')[0..-2].join }
9
+ table_names.each do |table_name|
10
+ Object.instance_eval do
11
+ define_method(table_name) do |*args|
12
+ table_name.camelize.constantize.send(:find, *args)
13
+ end
14
+ end
15
+ end
16
+ end
17
+ end
18
+ # note: Mike wrote this for ARec, but it works on ARes too since it doesn't hit the DB
@@ -0,0 +1,9 @@
1
+ # Rails verbosity: http://weblog.jamisbuck.org/2007/1/8/watching-activerecord-do-it-s-thing
2
+ # Marcel said they toyed with making this the console default on core
3
+ class Object
4
+ def log
5
+ ActiveRecord::Base.clear_active_connections!
6
+ ActiveRecord::Base.logger = Logger.new(STDOUT)
7
+ end
8
+ end
9
+
@@ -0,0 +1,72 @@
1
+ # String#to_proc
2
+ #
3
+ # See http://weblog.raganwald.com/2007/10/stringtoproc.html
4
+ #
5
+ # Ported from the String Lambdas in Oliver Steele's Functional Javascript
6
+ # http://osteele.com/sources/javascript/functional/
7
+ #
8
+ # This work is licensed under the MIT License:
9
+ #
10
+ # (c) 2007 Reginald Braithwaite
11
+ # Portions Copyright (c) 2006 Oliver Steele
12
+ #
13
+ # Permission is hereby granted, free of charge, to any person obtaining
14
+ # a copy of this software and associated documentation files (the
15
+ # "Software"), to deal in the Software without restriction, including
16
+ # without limitation the rights to use, copy, modify, merge, publish,
17
+ # distribute, sublicense, and/or sell copies of the Software, and to
18
+ # permit persons to whom the Software is furnished to do so, subject to
19
+ # the following conditions:
20
+ #
21
+ # The above copyright notice and this permission notice shall be
22
+ # included in all copies or substantial portions of the Software.
23
+ #
24
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
25
+ # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
26
+ # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
27
+ # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
28
+ # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
29
+ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
30
+ # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
31
+
32
+ class String
33
+ unless public_method_defined? :to_proc
34
+ def to_proc &block
35
+ params = []
36
+ expr = self
37
+ sections = expr.split(/\s*->\s*/m)
38
+ if sections.length > 1 then
39
+ eval_block(sections.reverse!.inject { |e, p| "(Proc.new { |#{p.split(/\s/).join(', ')}| #{e} })" }, block)
40
+ elsif expr.match(/\b_\b/)
41
+ eval_block("Proc.new { |_| #{expr} }", block)
42
+ else
43
+ leftSection = expr.match(/^\s*(?:[+*\/%&|\^\.=<>\[]|!=)/m)
44
+ rightSection = expr.match(/[+\-*\/%&|\^\.=<>!]\s*$/m)
45
+ if leftSection || rightSection then
46
+ if (leftSection) then
47
+ params.push('$left')
48
+ expr = '$left' + expr
49
+ end
50
+ if (rightSection) then
51
+ params.push('$right')
52
+ expr = expr + '$right'
53
+ end
54
+ else
55
+ self.gsub(
56
+ /(?:\b[A-Z]|\.[a-zA-Z_$])[a-zA-Z_$\d]*|[a-zA-Z_$][a-zA-Z_$\d]*:|self|arguments|'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"/, ''
57
+ ).scan(
58
+ /([a-z_$][a-z_$\d]*)/i
59
+ ) do |v|
60
+ params.push(v) unless params.include?(v)
61
+ end
62
+ end
63
+ eval_block("Proc.new { |#{params.join(', ')}| #{expr} }", block)
64
+ end
65
+ end
66
+ private
67
+ def eval_block(code, block)
68
+ eval code, block && block.binding
69
+ end
70
+ end
71
+ end
72
+
@@ -0,0 +1,30 @@
1
+ #--
2
+ # Copyright (c) 2005 David Heinemeier Hansson
3
+ #
4
+ # Permission is hereby granted, free of charge, to any person obtaining
5
+ # a copy of this software and associated documentation files (the
6
+ # "Software"), to deal in the Software without restriction, including
7
+ # without limitation the rights to use, copy, modify, merge, publish,
8
+ # distribute, sublicense, and/or sell copies of the Software, and to
9
+ # permit persons to whom the Software is furnished to do so, subject to
10
+ # the following conditions:
11
+ #
12
+ # The above copyright notice and this permission notice shall be
13
+ # included in all copies or substantial portions of the Software.
14
+ #
15
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16
+ # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17
+ # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18
+ # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19
+ # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20
+ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21
+ # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22
+ #++
23
+
24
+ class Symbol
25
+ unless public_method_defined? :to_proc
26
+ def to_proc
27
+ Proc.new { |*args| args.shift.__send__(self, *args) }
28
+ end
29
+ end
30
+ end
data/lib/themes.rb ADDED
@@ -0,0 +1,79 @@
1
+ module UtilityBelt
2
+ module Themes
3
+ def self.background(bkg)
4
+ case bkg
5
+ when :dark
6
+ Wirble::Colorize.colors = UtilityBelt::Themes::WIRBLE_DEFAULT_THEME
7
+ when :light
8
+ Wirble::Colorize.colors = UtilityBelt::Themes::THEME_FOR_WHITE_BKG
9
+ end
10
+ end
11
+ WIRBLE_DEFAULT_THEME = {
12
+ # delimiter colors
13
+ :comma => :blue,
14
+ :refers => :blue,
15
+
16
+ # container colors (hash and array)
17
+ :open_hash => :green,
18
+ :close_hash => :green,
19
+ :open_array => :green,
20
+ :close_array => :green,
21
+
22
+ # object colors
23
+ :open_object => :light_red,
24
+ :object_class => :white,
25
+ :object_addr_prefix => :blue,
26
+ :object_line_prefix => :blue,
27
+ :close_object => :light_red,
28
+
29
+ # symbol colors
30
+ :symbol => :yellow,
31
+ :symbol_prefix => :yellow,
32
+
33
+ # string colors
34
+ :open_string => :red,
35
+ :string => :cyan,
36
+ :close_string => :red,
37
+
38
+ # misc colors
39
+ :number => :cyan,
40
+ :keyword => :green,
41
+ :class => :light_green,
42
+ :range => :red,
43
+ }
44
+ THEME_FOR_WHITE_BKG = {
45
+ # delimiter colors
46
+ :comma => :purple,
47
+ :refers => :blue,
48
+
49
+ # container colors (hash and array)
50
+ :open_hash => :red,
51
+ :close_hash => :red,
52
+ :open_array => :red,
53
+ :close_array => :red,
54
+
55
+ # object colors
56
+ :open_object => :dark_gray,
57
+ :object_class => :purple,
58
+ :object_addr_prefix => :blue,
59
+ :object_line_prefix => :blue,
60
+ :close_object => :dark_gray,
61
+
62
+ # symbol colors
63
+ :symbol => :black,
64
+ :symbol_prefix => :light_gray,
65
+
66
+ # string colors
67
+ :open_string => :blue,
68
+ :string => :dark_gray,
69
+ :close_string => :blue,
70
+
71
+ # misc colors
72
+ :number => :black,
73
+ :keyword => :brown,
74
+ :class => :red,
75
+ :range => :blue,
76
+ }
77
+ COLORS = WIRBLE_DEFAULT_THEME
78
+ end
79
+ end
@@ -0,0 +1,39 @@
1
+ # This started as my (Giles Bowkett's) .irbrc file, turned into a recipe on IRB for the Pragmatic Programmers,
2
+ # and soon became a scrapbook of cool code snippets from all over the place. All the RDoc lives in the README.
3
+ # Check that file for usage information, authorship, copyright, and extensive details. This file contains the
4
+ # actual code (duh), and a bunch of links to relevant blog posts. You can also find a nice, HTMLified version
5
+ # of the README content at http://utilitybelt.rubyforge.org.
6
+
7
+ UTILITY_BELT_IRB_STARTUP_PROCS = {}
8
+
9
+ %w{rubygems
10
+ platform
11
+ wirble
12
+ net/http
13
+ tempfile}.each {|library| require library}
14
+ %w{init colorize}.each {|message| Wirble.send(message)}
15
+ %w{mac_clipboard
16
+ is_an
17
+ pastie
18
+ themes
19
+ irb_verbosity_control
20
+ rails_verbosity_control
21
+ command_history
22
+ not
23
+ language_greps
24
+ rails_finder_shortcut
25
+ amazon_upload_shortcut
26
+ irb_options
27
+ interactive_editor
28
+ string_to_proc
29
+ symbol_to_proc
30
+ with}.each {|internal_library| require internal_library}
31
+
32
+ # default: dark background
33
+ UtilityBelt::Themes.background(:dark)
34
+
35
+ # Called when the irb session is ready, after any external libraries have been loaded. I can't
36
+ # remember why I did this. it might be a cargo cult thing.
37
+ IRB.conf[:IRB_RC] = lambda do
38
+ UTILITY_BELT_IRB_STARTUP_PROCS.each {|symbol, proc| proc.call}
39
+ end
data/lib/with.rb ADDED
@@ -0,0 +1,21 @@
1
+ # Object#with -- by Dan Yoder, dev.zeraweb.com -- this is something from Pascal
2
+ # and JavaScript. here's the use case.
3
+
4
+ # instead of:
5
+ # some_object.do_x
6
+ # some_object.do_y
7
+ # some_object.do_z
8
+ #
9
+ # you can instead do:
10
+ # with(some_object)
11
+ # do_x
12
+ # do_y
13
+ # do_z
14
+ # end
15
+
16
+ class Object
17
+ def with(object, &block)
18
+ object.instance_eval &block
19
+ end
20
+ end
21
+
@@ -0,0 +1,40 @@
1
+ require "string_to_proc"
2
+ describe "String to Proc" do
3
+
4
+ before(:all) do
5
+ @one2five = 1..5
6
+ end
7
+
8
+ it "should handle simple arrow notation" do
9
+ @one2five.map(&'x -> x + 1').should eql(@one2five.map { |x| x + 1 })
10
+ @one2five.map(&'x -> x*x').should eql(@one2five.map { |x| x*x })
11
+ @one2five.inject(&'x y -> x*y').should eql(@one2five.inject { |x,y| x*y })
12
+ 'x y -> x**y'.to_proc()[2,3].should eql(lambda { |x,y| x**y }[2,3])
13
+ 'y x -> x**y'.to_proc()[2,3].should eql(lambda { |y,x| x**y }[2,3])
14
+ end
15
+
16
+ it "should handle chained arrows" do
17
+ 'x -> y -> x**y'.to_proc()[2][3].should eql(lambda { |x| lambda { |y| x**y } }[2][3])
18
+ 'x -> y z -> y**(z-x)'.to_proc()[1][2,3].should eql(lambda { |x| lambda { |y,z| y**(z-x) } }[1][2,3])
19
+ end
20
+
21
+ it "should handle the default parameter" do
22
+ @one2five.map(&'2**_/2').should eql(@one2five.map { |x| 2**x/2 })
23
+ @one2five.select(&'_%2==0').should eql(@one2five.select { |x| x%2==0 })
24
+ end
25
+
26
+ it "should handle point-free notation" do
27
+ @one2five.inject(&'*').should eql(@one2five.inject { |mem, var| mem * var })
28
+ @one2five.select(&'>2').should eql(@one2five.select { |x| x>2 })
29
+ @one2five.select(&'2<').should eql(@one2five.select { |x| 2<x })
30
+ @one2five.map(&'2*').should eql(@one2five.map { |x| 2*x })
31
+ (-3..3).map(&'.abs').should eql((-3..3).map { |x| x.abs })
32
+ end
33
+
34
+ it "should handle implied parameters as best it can" do
35
+ @one2five.inject(&'x*y').should eql(@one2five.inject(&'*'))
36
+ 'x**y'.to_proc()[2,3].should eql(8)
37
+ 'y**x'.to_proc()[2,3].should eql(8)
38
+ end
39
+
40
+ end
@@ -0,0 +1,2 @@
1
+ # yeah, I know. I know! but you try to write specs for code which launches vi. most of this was
2
+ # already written by the time I started tasting the BDD Kool-Aid.
File without changes
@@ -0,0 +1,22 @@
1
+ require 'rubygems'
2
+ SPEC = Gem::Specification.new do |s|
3
+ s.name = "utility_belt"
4
+ s.version = "1.0.0"
5
+ s.author = "Giles Bowkett"
6
+ s.email = "gilesb@gmail.com"
7
+ s.homepage = "http://utilitybelt.rubyforge.org"
8
+ s.platform = Gem::Platform::RUBY
9
+ s.summary = "A grab-bag of IRB power user madness."
10
+ s.files = Dir.glob("**/*")
11
+ %w{amazon google}.each do |command_line_utility_for_interacting_with_a_gigantic_self_aware_ai|
12
+ s.executables << command_line_utility_for_interacting_with_a_gigantic_self_aware_ai
13
+ end
14
+ s.require_path = "lib"
15
+ s.autorequire = "utility_belt"
16
+ s.test_file = "test/utility_belt_spec.rb"
17
+ s.has_rdoc = true
18
+ s.extra_rdoc_files = ["README"]
19
+ s.add_dependency("wirble", ">= 0.1.2")
20
+ s.add_dependency("aws-s3", ">= 0.4.0")
21
+ s.add_dependency("Platform", ">= 0.4.0")
22
+ end
metadata ADDED
@@ -0,0 +1,109 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: utility_belt
3
+ version: !ruby/object:Gem::Version
4
+ version: 1.0.0
5
+ platform: ruby
6
+ authors:
7
+ - Giles Bowkett
8
+ autorequire: utility_belt
9
+ bindir: bin
10
+ cert_chain: []
11
+
12
+ date: 2007-12-03 00:00:00 -08:00
13
+ default_executable:
14
+ dependencies:
15
+ - !ruby/object:Gem::Dependency
16
+ name: wirble
17
+ version_requirement:
18
+ version_requirements: !ruby/object:Gem::Requirement
19
+ requirements:
20
+ - - ">="
21
+ - !ruby/object:Gem::Version
22
+ version: 0.1.2
23
+ version:
24
+ - !ruby/object:Gem::Dependency
25
+ name: aws-s3
26
+ version_requirement:
27
+ version_requirements: !ruby/object:Gem::Requirement
28
+ requirements:
29
+ - - ">="
30
+ - !ruby/object:Gem::Version
31
+ version: 0.4.0
32
+ version:
33
+ - !ruby/object:Gem::Dependency
34
+ name: Platform
35
+ version_requirement:
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ">="
39
+ - !ruby/object:Gem::Version
40
+ version: 0.4.0
41
+ version:
42
+ description:
43
+ email: gilesb@gmail.com
44
+ executables:
45
+ - amazon
46
+ - google
47
+ extensions: []
48
+
49
+ extra_rdoc_files:
50
+ - README
51
+ files:
52
+ - bin
53
+ - bin/amazon
54
+ - bin/google
55
+ - History.txt
56
+ - lib
57
+ - lib/amazon_upload_shortcut.rb
58
+ - lib/command_history.rb
59
+ - lib/interactive_editor.rb
60
+ - lib/irb_options.rb
61
+ - lib/irb_verbosity_control.rb
62
+ - lib/is_an.rb
63
+ - lib/language_greps.rb
64
+ - lib/mac_clipboard.rb
65
+ - lib/not.rb
66
+ - lib/pastie.rb
67
+ - lib/rails_finder_shortcut.rb
68
+ - lib/rails_verbosity_control.rb
69
+ - lib/string_to_proc.rb
70
+ - lib/symbol_to_proc.rb
71
+ - lib/themes.rb
72
+ - lib/utility_belt.rb
73
+ - lib/with.rb
74
+ - Manifest.txt
75
+ - Rakefile
76
+ - README
77
+ - test
78
+ - test/string_to_proc_spec.rb
79
+ - test/utility_belt_spec.rb
80
+ - utility_belt-1.0.0.gem
81
+ - utility_belt.gemspec
82
+ has_rdoc: true
83
+ homepage: http://utilitybelt.rubyforge.org
84
+ post_install_message:
85
+ rdoc_options: []
86
+
87
+ require_paths:
88
+ - lib
89
+ required_ruby_version: !ruby/object:Gem::Requirement
90
+ requirements:
91
+ - - ">="
92
+ - !ruby/object:Gem::Version
93
+ version: "0"
94
+ version:
95
+ required_rubygems_version: !ruby/object:Gem::Requirement
96
+ requirements:
97
+ - - ">="
98
+ - !ruby/object:Gem::Version
99
+ version: "0"
100
+ version:
101
+ requirements: []
102
+
103
+ rubyforge_project:
104
+ rubygems_version: 0.9.5
105
+ signing_key:
106
+ specification_version: 2
107
+ summary: A grab-bag of IRB power user madness.
108
+ test_files:
109
+ - test/utility_belt_spec.rb