Class: Object

Inherits:
BasicObject
Defined in:
lib/extra/object.rb

Instance Method Summary collapse

Instance Method Details

#class_def(name, &block) ⇒ Object

whytheluckystiff: whytheluckystiff.net/articles/seeingMetaclassesClearly.html

Adds a class instance method.

Example:

SomeClass.class_def(:whoami) { 'I am SomeClass, silly!' }

SomeClass.whoami #=> "I am SomeClass, silly!"

Returns: A Proc object of the method, or nil.



54
55
56
# File 'lib/extra/object.rb', line 54

def class_def(name, &block)
	class_eval { define_method(name, &block) } if kind_of? Class
end

#deepcopyObject

Credit to the original author. This method retrieves a deep copy of the current object.

Returns: Deep copy of the same object.



63
64
65
# File 'lib/extra/object.rb', line 63

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

#meta_def(name, &block) ⇒ Object

whytheluckystiff: whytheluckystiff.net/articles/seeingMetaclassesClearly.html

Define an instance method on the metaclass.

Example: s = 'foo'; s.meta_def(:longer) { self * 2 }; s.longer #=> "foofoo"

Returns: A Proc object of the method.



38
39
40
# File 'lib/extra/object.rb', line 38

def meta_def(name, &block)
	meta_eval { define_method(name, &block) }
end

#meta_eval(&block) ⇒ Object

whytheluckystiff: whytheluckystiff.net/articles/seeingMetaclassesClearly.html

Evaluate code on the metaclass.

Example:

s = 'foo'; s.meta_eval { define_method(:longer) { self * 2 } }

s.longer #=> "foofoo"'

Returns: The block’s final expression.



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

def meta_eval(&block)
	metaclass.instance_eval(&block)
end

#metaclassObject

whytheluckystiff: whytheluckystiff.net/articles/seeingMetaclassesClearly.html

Gets a metaclass (a class of a class).

Example: 'hello'.metaclass #=> #<Class:#<String:0xb7a57998>>

Returns: The metaclass.



10
11
12
# File 'lib/extra/object.rb', line 10

def metaclass
	class << self; self; end
end

#to_boolObject

Convert object to boolean.

Example:

"foo".to_bool #=> true

false.to_bool #=> false

nil.to_bool #=> nil

true.to_bool #=> true

Returns: Boolean or nil.



81
82
83
84
85
86
87
# File 'lib/extra/object.rb', line 81

def to_bool
	if [FalseClass, NilClass].include? self.class
		self
	else
		true
	end
end