Ruby portal.new parent,klass

时间:2017-11-13 19:18:55

标签: ruby

所以我只是尝试在Module中创建一个Client类,然后在Client initialize方法中使用Portal Class来创建一个Response类。我正在尝试创建一种方法,允许Client类访问Response类方法和instance_variables。下面是我创建的粗略ruby文件和模块/类架构,用于测试所有这些:

module Test
    class Client

        attr_accessor :response

        def initialize
            conn
            @response = Portal.new self, Response
        end

        def conn
            @conn = Faraday.new(:url => 'http://api.openweathermap.org') do |faraday|
                faraday.request  :url_encoded             # form-encode POST params
                faraday.response :logger                  # log requests to STDOUT
                faraday.adapter  Faraday.default_adapter  # make requests with Net::HTTP
            end
        end
    end

    class Portal
        def initialize parent, klass
            @parent = parent
            @klass = klass
        end

        def method_missing method, *args, &block
            @klass.public_send method, @parent, *args, &block
        end
    end

    class Response

        attr_accessor :conn, :res

        def initialize client, params
            @client = client
            conn
        end

        def conn
            @conn
        end

        def get
            @res = conn.get do |req|
                    req.url '/data/2.5/weather'
                    req.params['q'] = @city_country_state
                    req.params['APPID'] = @consumer_api_key
                    req.params['units'] = @units
                end
        end
    end
end

使用binding.pry我“测试”了我的程序并收到了以下内容,最后只发生了错误:

[1] pry(main)> new = Test::Client.new
=> #<Test::Client:0x00007fbaca975540
 @conn=
  #<Faraday::Connection:0x00007fbaca975310.....>
@response=
  #<Test::Portal:0x00007fbaca96e1c8
   @klass=Test::Response,
   @parent=#<Test::Client:0x00007fbaca975540 ...>>>

在创建并看到Portal类创建一个Test :: Response类之后,我检查了Test :: Client @response变量:

[2] pry(main)> new.response
=> #<Test::Portal:0x00007fbaca96e1c8
 @klass=Test::Response,
 @parent=
  #<Test::Client:0x00007fbaca975540.....>

由于@response变量设置正确并且继承正确,我转到尝试并从new = Test :: Client.new中调用Test :: Response.get:

[3] pry(main)> new.response.get
NoMethodError: undefined method `get' for Test::Response:Class
from test.rb:47:in `public_send'

test.rb中的第47行引用了Test :: Portal行:

@klass.public_send method, @parent, *args, &block

method_missing函数中:

def method_missing method, *args, &block
    @klass.public_send method, @parent, *args, &block
end

如何允许创建的Test :: Client对象在Test :: Response中使用get方法,并在initialize方法中使用Test :: Client的@conn和conn方法设置@conn。

1 个答案:

答案 0 :(得分:0)

响应实例变量@conn永远不会设置,并且始终为nil我认为这是一个问题。现在你也试着调用Response.get但是get是一个实例方法所以也许尝试初始化@response为@response = Portal.new self,Response.new(conn,{})

Via:engineersmnky 11月13日20:29