Skip to content

Instantly share code, notes, and snippets.

@eric1234
Last active July 5, 2016 20:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eric1234/7815de006a299ad7acea8c71fa65af92 to your computer and use it in GitHub Desktop.
Save eric1234/7815de006a299ad7acea8c71fa65af92 to your computer and use it in GitHub Desktop.
Experiment in a Localized Extension

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.

module Kernel
def extension klass, method, &blk
mod = Module.new do
refine klass do
define_method method, &blk
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment