[英]Finding out where methods are defined in Ruby/Rails (as opposed to Java)
我剛剛開始使用Ruby on Rails。 來自Java世界,我想知道的一件事是Ruby / Rails開發人員如何找出實際定義方法的位置。
我習慣於單擊Eclipse中的方法來查找即使在第三方庫中定義的位置(假設我有源代碼)。
一個具體的例子:我試圖找出Authlogic gem如何顯然改變我的User類的構造函數以要求一個額外的參數(稱為:password_confirmation),即使User類甚至沒有繼承任何與Authlogic相關的東西。
可能我只是忽略了一些非常明顯的東西(或許我仍然無法圍繞整個“約定配置”的事情;-))
快速找到像Ruby這樣的動態語言的方法位置有點困難。
您可以使用object.methods
或object.instance_methods
快速找到方法。
如果您使用的是Ruby 1.9,則可以執行以下操作:
object.method(:method_name).source_location
有關source_location的更多信息 - 請單擊此處
Pry寶石專為這種探索性使用案例而設計。
Pry是一個交互式shell,它允許您使用類似shell的命令(如cd
和ls
瀏覽程序的源代碼。
您可以為所遇到的任何方法提取文檔,甚至可以查看源代碼,包括某些情況下的本機C代碼(使用pry-doc
插件)。 您甚至可以直接跳轉到使用edit-method
命令定義特定方法的文件/行。 show-method
和show-doc
命令還顯示了它們所采用的方法的精確位置。
觀看railscast截屏視頻以獲取更多信息。
以下是一些示例:
pry(main)> show-doc OpenStruct#initialize
From: /Users/john/.rvm/rubies/ruby-1.9.2-p180/lib/ruby/1.9.1/ostruct.rb @ line 46:
Number of lines: 11
visibility: private
signature: initialize(hash=?)
Create a new OpenStruct object. The optional hash, if given, will
generate attributes and values. For example.
require 'ostruct'
hash = { "country" => "Australia", :population => 20_000_000 }
data = OpenStruct.new(hash)
p data # -> <OpenStruct country="Australia" population=20000000>
By default, the resulting OpenStruct object will have no attributes.
pry(main)>
您還可以使用show-method
命令查找源代碼:
pry(main)> show-method OpenStruct#initialize
From: /Users/john/.rvm/rubies/ruby-1.9.2-p180/lib/ruby/1.9.1/ostruct.rb @ line 46:
Number of lines: 9
def initialize(hash=nil)
@table = {}
if hash
for k,v in hash
@table[k.to_sym] = v
new_ostruct_member(k)
end
end
end
pry(main)>
有關更多信息,請訪問http://pry.github.com :)
沒有人建議Pry gem提到了名為find-method
,這可能是作者所尋求的。
這是一個例子:
pry(main)> find-method current_user
Devise::Controllers::Helpers
Devise::Controllers::Helpers#current_user
WebsocketRails::ConnectionAdapters::Base
WebsocketRails::ConnectionAdapters::Base#current_user_responds_to?
然后,您可以按照@banister的提示瀏覽方法代碼。
有幾種方法可以更改現有類。 例如,如果要修改String類,請執行以下操作:
class String
def my_custom_method
puts "hello!"
end
end
但是還有其他選項,比如混合模塊或使用元編程添加/修改方法。
無論如何,有一些對象,你總是可以:
puts obj.methods.inspect
要么在代碼中執行,要么使用調試器。
另一種選擇是閱讀代碼。 特別是你應該閱讀gem的單元測試(./spec,...)。 有很多作者說單元測試使文檔過時了。
在Ruby中,您還可以使用mixins將class和instance方法添加到給定的類中。
基本上,如果您有一個模塊,您可以使用include和extend類方法將其方法添加到給定的類。 關於這些如何工作的簡短示例如下
Module A
def foo
"foo"
end
end
Module B
def bar
"bar"
end
end
Class YourClass
include A
extend B
end
p YourClass.new.foo # gives "foo" because the foo method is added as instance method
p YourClass.bar # gives "baz" because the bar method is added as class method
因為Ruby是一種動態語言,所以這些語句可以在任何地方使用。 因此,為了解決您的問題,不需要擴展authlogic類來獲取其方法。 許多插件在加載時使用此指令
ActiveRecord::Base.send :include, ModuleName
通過這種方式,它們告訴每個AR對象包含一些插件定義的模塊,並獲得AR對象中的所有方法。
許多acts_as
插件使用的另一種技術是僅在基類中使用acts_as
調用時才包含其模塊。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.