为什么我不能访问我的 class 实例方法?
Why can't I access my class instance methods?
我正在尝试从 MethodLogger 模块中访问 ApiClient class 实例方法。方法 return 每次都为空。
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
我认为也许基数不正确,但 returning Assets::ApiClient 是正确的。
有什么想法可能是错误的吗?
一旦包含模块(即作为 include MethodLogger
的一部分)调用,就会调用您包含的方法
那时 class 确实没有自己的实例方法 - 您只需在几行之后定义它们。
如果你看一下 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"
在您的行 include MethodLogger
中调用了该方法,此时您还没有定义任何方法。
我正在尝试从 MethodLogger 模块中访问 ApiClient class 实例方法。方法 return 每次都为空。
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
我认为也许基数不正确,但 returning Assets::ApiClient 是正确的。
有什么想法可能是错误的吗?
一旦包含模块(即作为 include MethodLogger
的一部分)调用,就会调用您包含的方法
那时 class 确实没有自己的实例方法 - 您只需在几行之后定义它们。
如果你看一下 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"
在您的行 include MethodLogger
中调用了该方法,此时您还没有定义任何方法。