Sha256: 6c5258733218ee2fe8e725f1e8744dbd06c999db784c7967071b3d62304db922

Contents?: true

Size: 1.12 KB

Versions: 4

Compression:

Stored size: 1.12 KB

Contents

# Copyright: Copyright (c) 2005  Nicolas Pouillard. All rights reserved.
# Author: Nicolas Pouillard  <ertai@lrde.epita.fr>.
# License: Gnu General Public License.

# $LastChangedBy: ertai $
# $Id: dumpable_proc.rb 190 2005-04-04 14:46:40Z ertai $

require 'yaml'
require 'delegate'

class DumpableProc < DelegateClass(Proc)

  def initialize ( str )
    @str = str.freeze
    super(eval("proc { #@str }"))
  end

  def _dump ( depth )
    Marshal.dump([self.class, @str])
  end

  def self._load ( data )
    klass, str = Marshal.load(data)
    klass.new(str)
  end

  def to_yaml ( opts={} )
    "#{to_yaml_type} #@str"
  end

  def to_s
    @str
  end

  def to_yaml_type
    '!proc'
  end

end

YAML.add_builtin_type('!proc') do |type, val|
  DumpableProc.new(val.to_s)
end

if defined? TEST_MODE or $0 == __FILE__

require 'test/unit'

class DumpableProcTest < Test::Unit::TestCase

  def test_simple
    p = DumpableProc.new('|x| 3 + x')
    assert_equal(7, p[4])
    str = nil
    assert_nothing_raised { str = Marshal.dump(p) }
    p2 = nil
    assert_nothing_raised { p2 = Marshal.load(str) }
    assert_equal(9, p2[6])
  end

end

end

Version data entries

4 entries across 4 versions & 2 rubygems

Version Path
ttk-0.1.576 ruby_ex/dumpable_proc.rb
ttk-0.1.580 ruby_ex/dumpable_proc.rb
ttk-0.1.579 ruby_ex/dumpable_proc.rb
vcs-0.2.148 ruby_ex/dumpable_proc.rb