Tuesday, 23 October 2012

Ruby: hiding method from an instance

This one is simple, for some reason I needed to hide a method from an instance so people would use my wrapper instead of the method directly - I have good reasons, but to achieve this we can, again, resort to instance_eval:

irb(main):001:0>  class A
irb(main):002:1>  def a
irb(main):003:2>  p 'hello world'
irb(main):004:2>  end
irb(main):005:1>  end
=> nil
irb(main):007:0*  a = A.new
=> #<A:0x0000001fbee140>
irb(main):008:0>  a.instance_eval do 
irb(main):009:1*  alias :b :a
irb(main):010:1> def a
irb(main):011:2> p 'you should not use this method'
irb(main):012:2> end
irb(main):013:1> end
=> nil
irb(main):014:0> a.a
"you should not use this method"
=> "you should not use this method"
irb(main):015:0> a.b
"hello world"
=> "hello world"