Class: Object

Inherits:
BasicObject
Defined in:
lib/objhax.rb

Overview

A collection of useful code bits that have been pilfered from various sources on the Interweb.

Instance Method Summary collapse

Instance Method Details

#class_def(name, &blk) ⇒ Object

Defines an instance method within a class



21
22
23
# File 'lib/objhax.rb', line 21

def class_def name, &blk
    class_eval { define_method name, &blk }
end

#deep_copyObject

Deep copy of objects that can be handled with Marshal



26
27
28
# File 'lib/objhax.rb', line 26

def deep_copy
    Marshal.load(Marshal.dump(self))
end

#instance_exec(*args, &block) ⇒ Object

Define, run and then undefine a method to fake instance_eval with arguments (not needed on 1.9)



32
33
34
35
36
37
38
39
40
41
# File 'lib/objhax.rb', line 32

def instance_exec(*args, &block)
    mname = "__instance_exec_#{Thread.current.object_id.abs}"
    class << self; self end.class_eval{ define_method(mname, &block) }
    begin
        ret = send(mname, *args)
    ensure
        class << self; self end.class_eval{ undef_method(mname) } rescue nil
    end
    ret
end

#meta_def(name, &blk) ⇒ Object

Adds methods to a metaclass



16
17
18
# File 'lib/objhax.rb', line 16

def meta_def name, &blk
    meta_eval { define_method name, &blk }
end

#meta_eval(&blk) ⇒ Object

Run a block in the context of the metaclass.



13
# File 'lib/objhax.rb', line 13

def meta_eval &blk; metaclass.instance_eval &blk; end

#metaclassObject

Return the metaclass of an object.



6
7
8
9
10
# File 'lib/objhax.rb', line 6

def metaclass 
    class << self
        self 
    end 
end