add a method to a class which can only be accessed in a specified class

You could use refinements for this:

Due to Ruby’s open classes you can redefine or add functionality to existing classes. This is called a “monkey patch”. Unfortunately the scope of such changes is global. All users of the monkey-patched class see the same changes. This can cause unintended side-effects or breakage of programs.

Refinements are designed to reduce the impact of monkey patching on other users of the monkey-patched class. Refinements provide a way to extend a class locally. Refinements can modify both classes and modules.

Something like this:

module HashPatches
  refine Hash do
    def new_hash_method
      # ...
    end
  end
end

and then:

class YourClass
  using HashPatches

  def m
    {}.new_hash_method
  end
end

That would let you call YourClass.new.m (which would use new_hash_method) but it wouldn’t pollute Hash globally so outside YourClass, some_hash.new_hash_method would be a NoMethodError.

Reading:

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top