为什么我无法访问我的类实例方法?

时间:2015-02-26 12:54:05

标签: ruby-on-rails instance-variables

我正在尝试从MethodLogger模块中访问ApiClient类实例方法。方法每次都返回空白。

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

我认为可能基数不正确,但它正确地返回了Assets :: ApiClient。

任何想法可能出错?

2 个答案:

答案 0 :(得分:2)

一旦包含该模块(即作为include MethodLogger)调用的一部分,就会调用您所包含的方法

此时该类确实没有自己的实例方法 - 您只需稍后定义几行。

答案 1 :(得分:0)

如果您查看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中调用该方法,此时您没有定义任何方法。