Sometimes I want to extend a core object to keep things object oriented but I want to limit the scope of my extension. Refinements provide a nice solution to that but for a single method extension I find it a bit bulky. Here is some standard syntax:
class SomeObject
module Extension
refine Array do
def average
sum.to_f / length
end
end
end
use Extension
def some_method
[...array off values...].average
end
end
In the above our method wants to average some values. We could of course keep this procedural, but I like the more OO-approach. Also this is a simple example and the OO approach is even more needed in other real worked use cases. I like the structure of this but it feels bulky. With the above helper our new code is:
class SomeObject
using extension(Array, :average) { sum.to_f / length }
def some_method
[...array off values...].average
end
end
If you need to add multiple methods to existing objects or use your extension in multiple contexts then the traditional refinement syntax is probably better but for a quick extension this works great.