Project

General

Profile

Actions

Feature #5582

open

Allow clone of singleton methods on a BasicObject

Added by thinkerbot (Simon Chiang) about 13 years ago. Updated almost 7 years ago.

Status:
Assigned
Target version:
-
[ruby-core:40805]

Description

Currently I do not know of a way to implement something like 'clone' on a BasicObject subclass. This is as close as I've gotten but as you can see the singleton methods are not propagated to the clone.

require 'test/unit'

class Context < BasicObject
  def _singleton_class_
    class << self
      SINGLETON_CLASS = self
      def _singleton_class_
        SINGLETON_CLASS
      end
    end
    _singleton_class_
  end

  def _class_
    _singleton_class_.superclass
  end

  def _extend_(mod)
    mod.__send__(:extend_object, self)
  end

  def _initialize_clone_(orig)
    # set variables as needed
  end

  def _clone_
    clone = _class_.allocate
    clone._initialize_clone_(self)
    _singleton_class_.included_modules.each {|mod| clone._extend_ mod }
    clone
  end
end

class ContextTest < Test::Unit::TestCase
  module A
    def a
      :a
    end
  end

  def test__clone__inherits_modules
    context = Context.new
    context._extend_ A
    clone = context._clone_
    assert_equal :a, clone.a
  end

  def test__clone__inherits_singleton_methods
    context = Context.new

    def context.a
      :a
    end

    clone = context._clone_
    assert_equal :a, clone.a  # fails
  end
end

Is there a way to do this that I don't see? If not, then I request that a way be added - perhaps by allowing the singleton_class to be set somehow.

In my case I am using Context as the context for a dsl where methods write to a target (an instance variable). I want to be able to clone a context such that I can have multiple contexts with the same methods, including extensions and singletons, that write to different targets.

Thank you.

Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0Like0