2017-11-13 11 views
1

私は単純にモジュール内にClientクラスを作成し、Client initializeメソッド内でPortalクラスを使用してResponseクラスを作成しようとしています。私は、クライアントクラスがResponseクラスメソッドとinstance_variablesにアクセスできるようにする方法を作成しようとしています。私は私のプログラムを「テスト」とだけエラーが最後に発生して、次のを受けbinding.pryを使用してRuby portal.new parent、klass

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 

:以下は、私はこのすべてをテストするために作成したラフなルビーのファイルおよびモジュール/クラスのアーキテクチャです: @response変数ので

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

[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 ...>>> 

は、内部テスト::レスポンスクラスを作成するポータルクラスを作成し、見た後、私はテスト::クライアント@response変数をチェック正しく設定して、私は新しい=テスト:: Client.new内からテスト:: Response.getを試みるに移動して呼び出す正しく継承されました:test.rbで

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

ライン47は、テストを指し::ポータルラインの:

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

私が作成したテスト:: Clientオブジェクトは、getを使用できるようにするにはどうすればよい:method_missing関数内

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

メソッドをTest :: Response内に作成し、Test :: Clientの@connおよびconnメソッドを使用して@connをinitializeメソッドで設定します。

+1

'Response'インスタンス変数' @ conn'は決して設定されず、常に 'nil'になります。これは問題だと思います。また、今では 'Response.get'を呼び出そうとしていますが、' get'はインスタンスメソッドなので、 '@response = Portal.new self、Response.new(conn、{})' – engineersmnky

答えて

0

応答インスタンス変数@connは設定されず、常にゼロになります。これは問題だと思います。 Response.new(conn、{})

Via:engineersmnky 11月13日に、Response.new(conn、{})のように@responseを初期化しようとすると、Response.getを呼び出そうとしています。 at 20:29