How to "disconnect" a certain method in ruby ​​from a call in the console

Say I have an ABC class with two methods.

class ABC
  def test
     "test"
  end

  def display_test
    puts test
  end
end

I only want to call ABC.new.display_testfrom my console (IRB) (returning me a “test”) and not be able to call ABC.new.testor ABC.new.send(:test). Is it possible? If so, how?

+4
source share
3 answers

The easiest way to do this is to have testprivate and override the method sendto specifically block the call 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

Note that this override is sendnot correct, because it takes only one parameter.

If you make the right path, it would be possible to do something like this:

ABC.new.send(:send, :test)
+5

.

:

class Foo
  private
  def bar
    # …
  end
end

:

class Foo
  def bar
    # …
  end
  private :bar
end

, : "" . , Ruby. :

Foo.new.send :bar
Foo.new.__send__ :bar
Foo.new.instance_eval { bar }

, , , : Ruby , . .

+2

. , send. Ruby.

, .

private :test

class TestClass
  def display_test
    puts test
  end

  private
    def test
      "test"
    end
end

:

puts TestClass.new.display_test
puts TestClass.new.send(:test)

begin
  puts TestClass.new.test
rescue
  puts "Error!"
end

+1

All Articles