[QUIZ] SerializableProc (#38)

R

Ruby Quiz

The three rules of Ruby Quiz:

1. Please do not post any solutions or spoiler discussion for this quiz until
48 hours have passed from the time on this message.

2. Support Ruby Quiz by submitting ideas as often as you can:

http://www.rubyquiz.com/

3. Enjoy!

-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

I'm a Proc addict. I use them all over the place in my code. Because of that,
whenever I end up needing persistence and I call Marshal.dump() or YAML.dump()
on some object hierarchy, I get to watch everything explode (since Procs cannot
be serialized).

This week's Ruby Quiz is to build a Proc that can be serialized.

I'm not aware of any possible way to add serialization capabilities to Ruby's
core Proc, which rules out a complete solution. However, even if what we build
is a hack, at least one person finds it super useful.

The task then is to build SerializableProc. It should support being serialized
by Marshal, PStore, and YAML and otherwise behave as close to a Proc as
possible. Put another way, make the following code run for your creation:

require "pstore"
require "yaml"

code = # Build your SerializableProc here!

File.open("proc.marshalled", "w") { |file| Marshal.dump(code, file) }
code = File.open("proc.marshalled") { |file| Marshal.load(file) }

code.call

store = PStore.new("proc.pstore")
store.transaction do
store["proc"] = code
end
store.transaction do
code = store["proc"]
end

code.call

File.open("proc.yaml", "w") { |file| YAML.dump(code, file) }
code = File.open("proc.yaml") { |file| YAML.load(file) }

code.call
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,780
Messages
2,569,608
Members
45,241
Latest member
Lisa1997

Latest Threads

Top