public
Last active

  • Download Gist
gistfile1.rb
Ruby
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
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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.