This post originated from an RSS feed registered with Ruby Buzz
by Ryan Davis.
Original Post: Rash of Ruby Releases
Feed Title: Polishing Ruby
Feed URL: http://blog.zenspider.com/index.rdf
Feed Description: Musings on Ruby and the Ruby Community...
I just finished releasing a WHOLE bunch o' stuff, all gemified and cleaned up, mainly so that we could contribute the following solution to this week's ruby quiz (serializable procs):
require 'r2c_hacks'
class ProcStore # We have to have this because yaml calls allocate on Proc
def initialize(&proc)
@p = proc.to_ruby
end
def call(*args)
eval(@p).call(*args)
end
end
code = ProcStore.new { |x| return x+1 }
=> #<ProcStore:0x3db25c @p="proc do |x|\n return (x + 1)\nend">
OK, well, that obviously isn't the whole solution, but now that we've added Proc.to_ruby, it really is that simple. To see how simple it really is, check out our implementation:
class Proc
ProcStoreTmp = Class.new unless defined? ProcStoreTmp
def to_ruby
ProcStoreTmp.send(:define_method, :myproc, self)
m = ProcStoreTmp.new.method(:myproc)
result = m.to_ruby.sub!(/def myproc\(([^\)]+)\)/, 'proc do |\1|')
return result
end
end
We would have bypassed ProcStore entirely had we known how to get YAML to not call allocate on Proc when it was loading a proc back in. But, we were tired.
+ 2 minor enhancements:
+ Changed inline to take the language and a hash of options.
+ Still backwards compatible, for now, and emits a warning.
+ Options are available via the builder passed to your block.
+ 2 bug fixes:
+ Modified caller discovery, yet again, due to changes in ruby 1.8.3.
+ More compatible and clean with non-gems systems.
+ 3 bug fixes:
+ Fixed rubygem requires for non-gem systems.
+ Renamed on to on_error_in to make more clear.
+ Moved exceptions to their own tree to make catching cleaner.
+ 1 minor enhancements
+ Added gemspec (hastily).
+ 2 bug fixes
+ Translates bool type to VALUE since we were using Qtrue/Qfalse.
+ Fixed rubygems for non-gem systems.
+ 4 minor enhancements:
+ Added Graph#save and edge accessors for customizations.
+ Added Proc#to_ruby in r2c_hacks.
+ Added RubyToRuby#rewrite_defn to support bmethods (read: procs).
+ Added Class#optimize(*methods) to zenoptimize.
+ Added bin/nopaste for cmdline access to nopaste on rafb.net.
+ Added bin/quickbench to generate ruby benchmark templates quickly.
+ 4 bug fixes:
+ Fixed gems for non-gem systems.
+ Fixed minor output problem with RubyToRuby#process_defn.
+ Added some minor (performance) enhancements to zenoptimize.
+ Added requirements to gemspec to quell whining.