undef - Why would you want to undefine a method in ruby?

前端 未结 7 650
无人共我
无人共我 2020-12-15 09:41

I\'ve never seen undef - or any thing else that allows you to undefine a method - in any other programming languages. Why is it needed in Ruby?

EDIT: I\'m not arguin

7条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-15 10:22

    If your using Single Table Inheritance with an ORM, such as ActiveRecord, you may want to undefine the methods for fields which are not being used for a particular class/object.

    # table: shapes, with columns: name, sides, radius, type
    class Shape < ActiveRecord::Base
    end
    
    class Circle < Shape
    end
    
    class Square < Shape
      undefine_method :radius
    end
    

    Note: This doesn't actually work in ActiveRecord as it internally expects a method for every field to always be defined.

    Note: A square does have a radius its just not commonly used, but you get the gist? Think of some property your storing in the database which a Circle has, but a Square does not.

提交回复
热议问题