Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to 'disable' a certain method in ruby from being called in the console

Tags:

ruby

Let's say I have a class ABC with two methods.

class ABC
  def test
     "test"
  end

  def display_test
    puts test
  end
end

I only want to be able to call ABC.new.display_test from my console (IRB) (returning me 'test') and not be able to call ABC.new.test or ABC.new.send(:test) for that matter. Is this possible? If so, how?

like image 489
Biketire Avatar asked Dec 17 '13 16:12

Biketire


1 Answers

The most thorough way to do so would be to have test private and override the send method to specifically block the call to test:

class ABC
  def test
     "test"
  end

  private :test

  def display_test
    puts test
  end

  def send(id)
    if id == :test
      raise NoMethodError.new("error")
    else
      super(id)
    end
  end

  alias_method :__send__, :send
end

Please note that this send override is not a proper one, as it only accepts a single parameter.

If done the right way, it would become possible to do something like this:

ABC.new.send(:send, :test)
like image 99
SirDarius Avatar answered Oct 19 '22 18:10

SirDarius