如何获取模型方法,不包括继承的、嵌入的、由rails生成的、getter、setter、验证器等



我有一个关于模型方法列表的问题。我想获得在我的模型中定义的方法列表,除了getter, setter和Rails生成的方法,验证方法等。一般来说,I取决于程序员从头到尾定义的方法。

使用:

Model.instance_methods (false) - Object.methods

获取我定义的方法以及ActiveRecord生成的方法。我怎么才能得到我想要的?

把这个放到你的~/.irbc

# Easily print methods local to an object's class
class Object
  def local_methods
    (methods - Object.instance_methods).sort
  end
end

像这样使用#local_methods方法:

>> class BasketballPlayer
>>   attr_accessor :name
>> 
?>   def champion?
>>     name == "Kevin Garnett"
>>   end
>> end
=> nil
>> kevin_garnett = BasketballPlayer.new
=> #<BasketballPlayer:0x11988f8>
>> kevin_garnett.name = "Kevin Garnett"
=> "Kevin Garnett"
>> kevin_garnett.champion?
=> true
>> kevin_garnett.local_methods
=> ["champion?", "name", "name="]

来源:http://robots.thoughtbot.com/post/159806033/irb-script-console-tips

最新更新