Skip to content

Instantly share code, notes, and snippets.

@nusco
nusco / .travis.yml
Created August 9, 2011 14:32
Example Travis configuration file
rvm: # list all the Rubies you want to test against
- 1.9.3
- jruby
- rbx
script: "bundle exec rake test" # your test command goes here
@nusco
nusco / after_method_missing.rb
Created October 4, 2010 16:05
Post: The method_missing() Chainsaw
class DoNotDisturb
def initialize
@desk = InformationDesk.new
end
def method_missing(name, *args)
unless name.to_s == "emergency"
hour = Time.now.hour
raise "Out for lunch" if hour >= 12 && hour < 14
end
@nusco
nusco / before_method_missing_1.rb
Created October 4, 2010 16:04
Post: "The method_missing() Chainsaw"
class InformationDesk
def emergency
# Call emergency...
"emergency() called"
end
def flights
# Provide flight information...
"flights() called"
end
@nusco
nusco / method_missing_example.rb
Created September 13, 2010 12:45
Post: The "method_missing()" Chainsaw
class Performer
def method_missing(name, *args)
"The duck will #{name}: #{args[0]}"
end
end
duck = Performer.new
duck.sing("Quacking in the Rain") # => "The duck will sing: Quacking in the Rain"
duck.dance("Swan Lake") # => "The duck will dance: Swan Lake"
@nusco
nusco / symbol_to_proc.rb
Created August 18, 2010 15:36
Spell: Symbol to Proc
# =====================
# Spell: Symbol to Proc
# =====================
# Convert a symbol to a block that calls a single method.
[1, 2, 3, 4].map(&:even?) # => [false, true, false, true]
# For more information: http://www.pragprog.com/titles/ppmetr/metaprogramming-ruby
@nusco
nusco / shared_scope.rb
Last active September 5, 2015 18:55
Spell: Shared Scope
# ===================
# Spell: Shared Scope
# ===================
# Share variables among multiple contexts in the same Flat Scope (https://gist.github.com/nusco/535082).
lambda {
shared = 10
self.class.class_eval do
@nusco
nusco / self_yield.rb
Created August 18, 2010 15:32
Spell: Self Yield
# =================
# Spell: Self Yield
# =================
# Pass self to the current block.
class Person
attr_accessor :name, :surname
def initialize
@nusco
nusco / scope_gate.rb
Created August 18, 2010 15:31
Spell: Scope Gate
# =================
# Spell: Scope Gate
# =================
# Isolate a scope with the class, module, or def keyword.
a = 1
defined? a # => "local-variable"
module MyModule
@nusco
nusco / sandbox.rb
Created August 18, 2010 15:30
Spell: Sandbox
# ==============
# Spell: Sandbox
# ==============
# Execute untrusted code in a safe environment.
def sandbox(&code)
proc {
$SAFE = 2
yield
@nusco
nusco / pattern_dispatch.rb
Created August 18, 2010 15:28
Spell: Pattern Dispatch
# =======================
# Spell: Pattern Dispatch
# =======================
# Select which methods to call based on their names.
$x = 0
class C
def my_first_method