[英]Why can't I access my class instance methods?
I'm trying to access the ApiClient class instance methods from within the MethodLogger module. 我正在尝试从MethodLogger模块内部访问ApiClient类实例方法。 Methods return empty every time. 方法每次都返回空。
require 'faraday'
module Assets
module MethodLogger
def self.included(base)
methods = base.instance_methods(false)
puts base # returns Assets::ApiClient
puts methods.length # returns 0
end
end
class ApiClient
include MethodLogger
def initialize(url, username = nil, password = nil)
@connection = Faraday.new(url) do |faraday|
faraday.basic_auth(username, password) if username
faraday.request :url_encoded
faraday.response :logger
faraday.adapter :net_http
faraday.use Errors::RaiseError
end
end
def get(path, parameter = nil)
@connection.get path, parameter
end
def post(path, data, headers = {})
@connection.post path, data, headers
end
def put(path, data, headers = {})
@connection.put path, data, headers
end
def delete(path)
@connection.delete path
end
end
end
I thought that perhaps the base was incorrect, but it is correctly returning Assets::ApiClient. 我以为这个基数可能不正确,但是它正确地返回了Assets :: ApiClient。
Any ideas what may be wrong? 任何想法可能有什么问题吗?
Your included method is called as soon as the module is included (ie as part of the include MethodLogger
) call 包含模块(即作为include MethodLogger
一部分)调用后,将立即调用您包含的方法
At that point the class does have no instance methods of its own - you only define those a couple of lines later. 那时,该类没有自己的实例方法-您仅在几行后定义它们。
If you take a look at the documentation of included : 如果您查看包含的文档 :
module A
def A.included(mod)
puts "#{self} included in #{mod}"
end
end
module Enumerable
include A
end
# => prints "A included in Enumerable"
The method is called in your line include MethodLogger
and at this point you don't have any method defined. 该方法在您的行include MethodLogger
被调用,此时您尚未定义任何方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.