【问题标题】:Why can't I access my class instance methods?为什么我不能访问我的类实例方法?
【发布时间】:2015-02-26 12:54:04
【问题描述】:

我正在尝试从 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。

有什么想法可能是错的吗?

【问题讨论】:

    标签: ruby-on-rails instance-variables


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-10-25
        • 2019-11-23
        • 2014-03-28
        • 2018-07-31
        • 2014-12-20
        • 1970-01-01
        • 2015-12-01
        • 2014-04-02
        相关资源
        最近更新 更多