Jay-Ar Polidario
Jay-Ar Polidario

Reputation: 6603

Making an instance method inaccessible from a subclass

Given:

class Base
  def foo
    puts 'foo!!!'
  end
end

class Ball < Base
end

I want:

  1. Ball.new.foo to return an error: No Method Found.
  2. Base.new.foo to return: foo!!!.

My attempts are:

Any ideas how to make both 1. and 2. work?

Background of the Problem

I have an ApplicationController action def routing_error that handles all remaining undefined routes. The problem with this is all all of the other controllers that inherits ApplicationController also inherits that action, in which I wanted it to be not. I could create a separate controller with just the action def routing_error but I feel it is overkill, and is just wondering first if there is another way to solve this.

Upvotes: 3

Views: 129

Answers (1)

sawa
sawa

Reputation: 168101

Do:

class Ball < Base
  undef_method :foo
end

If you want to undefine the method for many classes and you don't want to write the code like the above for each of them, then create a class in between.

class Dummy < Base
  undef_method :foo
end

class Base < Dummy
end

class Base2 < Dummy
end

...

Upvotes: 7

Related Questions