Skip to content

Instantly share code, notes, and snippets.

@abriening
Created May 12, 2009 14:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abriening/110515 to your computer and use it in GitHub Desktop.
Save abriening/110515 to your computer and use it in GitHub Desktop.
require 'yaml'
# yaml-able proc
# write the proc as a string or a block that returns a string
# no bindings!
class Sproc
def initialize *args, &block
@proc_string = block_given? ? block.call.to_s : args.first.to_s
end
def to_proc
@proc ||= eval(to_s)
end
def to_s
"Proc.new{ #{@proc_string} }"
end
def to_yaml
@proc = nil
super
end
# passes everything through to the instantiated proc
# including ``call'' and ``[]''
def method_missing *args
to_proc.send *args
end
end
if __FILE__ == $0
sproc = Sproc.new(' |n| n * n ')
sproc[10] == 100 or fail("Bad args.first mojo")
puts "#{sproc}[10] == 100: passed, from args.first"
sproc = Sproc.new do
" |n| n * n "
end
sproc[10] == 100 or fail("Bad block mojo")
puts "#{sproc}[10] == 100: passed, from block"
YAML::load(sproc.to_yaml)[10] == 100 or fail("Bad yaml mojo")
puts "YAML::load(sproc.to_yaml)[10] == 100: passed"
sproc.arity == 1 or fail("Bad pass thru to proc mojo")
puts "#{sproc}.arity == 1"
sproc = Sproc.new(' |*args| args.inject(0){|m,n| m + n } ')
sproc[1,2,3,4,5] == 15 or fail("Bad *args mojo")
puts "#{sproc}[1,2,3,4,5] == 15: passed"
sproc.arity == -1 or fail("Bad pass thru to proc mojo")
puts "#{sproc}.arity == -1: passed"
puts "Tests passed: #{sproc}, Yay!"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment