Skip to content

Instantly share code, notes, and snippets.

@joshuaclayton
Created October 23, 2008 21:26
Show Gist options
  • Save joshuaclayton/19216 to your computer and use it in GitHub Desktop.
Save joshuaclayton/19216 to your computer and use it in GitHub Desktop.
# This would go within your ~/.irbrc file
#
# The idea behind this is that you can store blocks of code not within clipboard or a
# misc. file, but within IRB, when hacking at code
#
# Snip is a singleton class that holds all your snippets for the current session
# An instance method 'snip' was also added to Object to allow for super-simple snip creation
#
# Here's a demo from IRB
#
# >> snip :test do
# ?> puts 1 + 2
# >> end
# => [:test]
# >> snip :test
# 3
# => nil
# >> snip :new_user do
# ?> User.new do |u|
# ?> u.first_name = "Josh"
# >> u.last_name = "Clayton"
# >> u.email = "[email protected]"
# >> end
# >> end
# => [:test, :new_user]
# >> snip :new_user
# => #<User id: nil, email: "[email protected]", login: nil, crypted_password: nil, salt: nil, remember_token: nil, activation_code: nil, state: "passive", first_name: "Josh", last_name: "Clayton", activated_at: nil, remember_token_expires_at: nil, deleted_at: nil, created_at: nil, updated_at: nil>
#
# Obviously, this is pretty beneficial if you're dealing with a block of code that you want to reuse; most other stuff can be done with IRB history
class Snip
class SnippetNotFoundError < StandardError; end
@@snips = {}
def self.create(name, &blk)
@@snips[name.to_s] = blk
@@snips.keys
end
def self.[](name)
raise SnippetNotFoundError, "the snippet '#{name.to_s}' was not found" unless @@snips.has_key?(name.to_s)
@@snips[name.to_s].call
end
def self.clear
@@snips.clear
end
def self.snips
@@snips
end
end
class Object
def snip(name, &blk)
if block_given?
Snip.create(name, &blk)
else
Snip[name]
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment