Method: Object#singleton_send
- Defined in:
- lib/quality_extensions/object/singleton_send.rb
#singleton_send(moduule, message, *args, &block) ⇒ Object Also known as: ss
Creates a singleton method and then calls it.
More specificaly, it extends self with the methods from moduule and then sends the supplied message and args (if any).
Examples:
"whatever".ss(MyColorizer, :colorize, :blue)
Advantages:
-
Keeps things object-oriented. Better than having global/class methods.
-
(
"whatever".ss(MyColorizer, :colorize).ss(SomeOtherClass, :another_class_method)instead of-
SomeOtherClass::another_class_method(MyColorizer::colorize("whatever")))
-
-
Method calls are listed in the order in which they are called.
-
-
Still lets you keep your methods in a namespace.
-
Doesn’t clutter up the base classes with methods that are only useful within a very small context. The methods are only added to the objects you specify. So you can “use” the base class without cluttering up all instances of the class with your methods.
-
Useful for cases where creating a subclass wouldn’t help because the methods you are calling would still return instances of the base class.
Disadvantages:
-
You have to have/create a module for the functions you want to use.
-
Can’t just call .sigleton_send(self, :some_method) if you want to use
some_methodthat’s defined inself. -
So what do we call the module containing the “singleton method”? String::MyColorizer? MyColorizer::String? MyStringColorizer?
-
Adding methods to the base class using Facets’ own namespacing facilities (Module#namespace and Module#include_as) might actually be a more sensible alternative a lot of the time than bothering to create singleton methods for single objects! That would look somethig like:
class String
namespace :my_colorizer do
def colorize(...); ...; end
end
end
"whatever".my_colorizer.colorize(:blue)
or
class String
include_as :my_colorizer => MyColorizer
end
"whatever".my_colorizer.colorize(:blue)
63 64 65 66 |
# File 'lib/quality_extensions/object/singleton_send.rb', line 63 def singleton_send(moduule, , *args, &block) self.extend(moduule) self.send(, *args, &block) end |