module MetaInstance::InstanceMethodDefine

This is based on a few things from reference.jumpingmonkey.org/programming_languages/ruby/ruby-metaprogramming.html

allows the adding of methods to instances, but not the entire set of instances for a particular class

Constants

METHOD_BACKUP_KEY

when a method is stubbed with snapshot data, we stare the original method prixefixed with this:

Public Instance Methods

backup_method(name) click to toggle source

backs up a method in case we want to restore it later

# File lib/meta_instance/instance_method_define.rb, line 34
def backup_method(name)
  meta_eval {
    alias_method "#{METHOD_BACKUP_KEY}#{name}", name
  }
end
define_method(name, &block) click to toggle source

Adds methods to a singletonclass define_singleton_method(name, &block) is the same as doing

meta_eval {

define_method(name, &block)

}

# File lib/meta_instance/instance_method_define.rb, line 29
def define_method(name, &block)
  define_singleton_method(name, &block)
end
instance_override(name, &block) click to toggle source

backs up and overrides a method. but don't override if we already have overridden this method

# File lib/meta_instance/instance_method_define.rb, line 16
def instance_override(name, &block)
  unless respond_to?("#{METHOD_BACKUP_KEY}#{name}")
    backup_method(name)
  end
  define_method(name, &block)
end
restore_method(name) click to toggle source

the original method becomes reaccessible

# File lib/meta_instance/instance_method_define.rb, line 41
def restore_method(name)
  if respond_to?("#{METHOD_BACKUP_KEY}#{name}")
    meta_eval {
      alias_method name, "#{METHOD_BACKUP_KEY}#{name}"
      remove_method "#{METHOD_BACKUP_KEY}#{name}"
    }
  end
end

Private Instance Methods

meta_eval(&block) click to toggle source

evals a block inside of a singleton class, aka

class << self

self

end

# File lib/meta_instance/instance_method_define.rb, line 57
def meta_eval(&block)
  singleton_class.instance_eval(&block)
end