Module: DeepClonable::ClassMethods

Defined in:
lib/deep_clonable.rb

Instance Method Summary collapse

Instance Method Details

#clone_method(clone_method_name, method_name = nil) ⇒ Object

Use this to define cloning version of the given in-place methods.

This method supports a common idiom where you create in-place and cloning versions of most operations. This method allows you to define only the in-place version (with the trailing bang (!), that part is important) and specify the cloning versions by name using this method.



54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/deep_clonable.rb', line 54

def clone_method(clone_method_name, method_name = nil)
  clone_method_name = clone_method_name.to_s.gsub(/\!$/,'')
  method_name ||= "#{clone_method_name}!"
  class_eval %{
    def #{clone_method_name}(*args, &block)
      self.clone do |object|
        object.#{method_name}(*args)
        block ? block.call(object) : object
      end
    end
  }
end