Thanks to Ruby powerful meta programming capability and Rails delegate
syntax, we can easily write graceful singleton class which makes the class works like a instance.
In traditional language such as C#, usually we write singleton code like this:
|
|
The previous approach works fine but the code that uses Foo
will be kind of ugly. Every time when we want to invoke the method Bar
on Foo
, we need to write Foo.Instance.Bar()
rather than more graceful way Foo.Bar()
.
To solve this problem we need implement the class in this way:
|
|
This approach simplified the caller code but complicated the declaration. You can use some trick such as Code-Snippet or code generating technology such as Text Template or CodeSmith to generate the dull delegation code. But it is still not graceful at all.
If we write same code in ruby, things become much easier, great thanks to Ruby’s powerful meta programming capability.
|
|
So in ruby solution we just use one statement delegate *Foo::Base.instance_methods, :to => :instance
then delegate all methods defined in base to instance.
Besides this solution, there is also another kind of cheaper but working solution:
Two different approaches make the code behaves slightly different, but anyway they both works.