Class: Object
- Inherits:
- BasicObject
- Defined in:
- lib/kitchensink/patches/object.rb,
lib/kitchensink/patches/object.rb,
lib/kitchensink/patches/object.rb,
lib/kitchensink/patches/object.rb
Class Method Summary collapse
-
.class_method(name) ⇒ Object
Returns an
UnboundMethod
representing a given class method in a class. -
.define_class_method(name, method = nil, &block) ⇒ Object
Works like define_method, only creates a class method.
-
.remove_class_method(name) ⇒ Object
Removes a class method.
Instance Method Summary collapse
-
#included_in?(collection) ⇒ Boolean
True if a collection includes this object.
Class Method Details
.class_method(name) ⇒ Object
Returns an UnboundMethod
representing a given class method in a class.
See Also: instance_method
Examples:
sc = String.class_method(:superclass)
sc.bind(String).call()
=> Object
– Note that here we use the “class << self; self; end.send” trick, which gives us access to the singleton class rather than the class itself. Setting instance methods here causes the subclass to receive class methods. Yay!
16 17 18 |
# File 'lib/kitchensink/patches/object.rb', line 16 def self.class_method(name) class << self; self; end.send :instance_method, name end |
.define_class_method(name, method = nil, &block) ⇒ Object
Works like define_method, only creates a class method.
-
define_class_method(symbol, method)
=> new_method -
define_class_method(symbol) {block}
=> proc
Examples:
String.define_class_method :get_parent_class, String.class_method(:superclass)
String.define_class_method :make_runon do |str, num|
String.new(str) * num
end
String.make_runon "abc", 3
=> "abcabcabc"
35 36 37 38 39 40 41 |
# File 'lib/kitchensink/patches/object.rb', line 35 def self.define_class_method(name, method=nil, &block) if method class << self; self; end.send :define_method, name, method else class << self; self; end.send :define_method, name, &block end end |
.remove_class_method(name) ⇒ Object
Removes a class method.
61 62 63 |
# File 'lib/kitchensink/patches/object.rb', line 61 def self.remove_class_method(name) class << self; self; end.send :remove_method, name end |
Instance Method Details
#included_in?(collection) ⇒ Boolean
True if a collection includes this object.
Note: I wrote this because sometimes collection.include?(object)
violates left-to-right reading order, such as when object
is more important than the collection
.
52 53 54 |
# File 'lib/kitchensink/patches/object.rb', line 52 def included_in?(collection) collection.include? self end |