Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby - remove inherited methods

Tags:

ruby

Is it possible to remove some of the inherited methods in Ruby? I mean, I can override it, but is there any other way?

Class ABC
end

a = ABC.new

puts a.id

Here, the method id is inherited from Object along with other methods like tap,class,type etc. I want to remove such methods.

Edit: I'm using Ruby 1.8.7

like image 546
huhukitty Avatar asked Aug 10 '11 15:08

huhukitty


3 Answers

Yes - undef_method :foo will prevent any calls to the method foo (contrasted with remove_method :foo, which removes the method from the child, but still passes through up the inheritance chain).

Once again, though, why do you want to remove things like id?

like image 189
Chowlett Avatar answered Oct 29 '22 19:10

Chowlett


You can always create a blank slate class to derive from:

class BlankSlate
  instance_methods.each do |m|
    undef_method(m) unless (m.match(/^__/))
  end
end

This should strip out all methods except for the internal ones that you're not supposed to mess with, like __send__.

like image 42
tadman Avatar answered Oct 29 '22 18:10

tadman


As tadman said you can make a BlankSlate object, or in ruby 1.9, there is the BasicObject class that has a bare minimum of methods. A quick google search turned up this for further reading: http://www.humbug.in/docs/ruby-best-practices/I_sect13_d1e2654.html

It appears that Rails already has BlankSlate built in: http://rubydoc.info/docs/rails/2.3.8/BlankSlate

like image 27
DGM Avatar answered Oct 29 '22 20:10

DGM