我在我的rails應用程式的目錄中添加了一些代碼,/lib/可能由于加載,它甚至沒有被rails識別,所以我將它移動到/app/lib/它至少被識別,但在呼叫模塊內的方法時沒有得到NoM??ethodError。這是我放入的一些代碼app/lib
# frozen_string_literal: true
module Github
module Auth
def connection
Faraday.new(
url: 'https://github.com'
)
end
def authorize
connection.get(
'/login/oauth/authorize',
params: {
client_id: '<My client id here>',
redirect_uri: '<My callback here>'
}
)
end
end
end
然后我有一個AuthorizeController類,我想從中呼叫這段代碼;
class AuthorizeController < ApplicationController
def index
response = Github::Auth.authorize
redirect_to response[:location] , allow_other_host: true
end
end
為此,我收到以下錯誤:

就像我說的那樣,我將代碼從其中移到了/lib/至少/app/lib/讓 Rails 能夠識別代碼的地方,但這對我來說感覺很笨拙,可能不是最好的方法。我也不想只為這個功能寫一個完整的gem
我以前在控制器中有這段代碼,但我希望它在 lib.xml 中。實作這一目標的最佳實踐是什么?
感謝 Rails 菜鳥!:)
uj5u.com熱心網友回復:
該錯誤與檔案位置無關 - 如果你想定義一個“模塊方法”,你需要定義它self:
module Github
module Auth
def self.connection
Faraday.new(
url: 'https://github.com'
)
end
def self.authorize
connection.get(
'/login/oauth/authorize',
params: {
client_id: '<My client id here>',
redirect_uri: '<My callback here>'
}
)
end
end
end
模塊的實體方法僅在封裝物件中可用 - 例如包含模塊的類的實體。
您還可以使用奇怪的命名Module#module_function方法從單例中提供對模塊實體方法的訪問:
module Github
module Auth
def connection
Faraday.new(
url: 'https://github.com'
)
end
def authorize
connection.get(
'/login/oauth/authorize',
params: {
client_id: '<My client id here>',
redirect_uri: '<My callback here>'
}
)
end
module_function :connection, :authorize
end
end
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/524645.html
標籤:轨道上的红宝石红宝石
上一篇:liferea:使用liferea.css更改文本大小
下一篇:如何在Rails中創建淺層路線?
