我有一个关于模型方法列表的问题。我想获得在我的模型中定义的方法列表,除了 getter、setter 和 Rails 生成的方法、验证方法等。一般来说,我依赖于程序员从头到尾定义的方法。
使用:
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
关于ruby-on-rails - 如何获取不包括继承、嵌入、由 rails、getter、setter、验证器 a 和其他生成的模型方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8430329/