簡體   English   中英

如何在 rake 任務中使用 controller 中定義的 function?

[英]How can I use a function defined in a controller in rails in a rake task?

我在我的 rails controller 中定義了一個 API function,另一個是我使用腳手架創建的數據庫。 `

  def function
    @results = HTTParty.get( $baseurl + "/extention", :headers => {
      $apikey => $apivalue,
      "Content-Type" => "application/json"
    })
    render json: @results.body
  end

`

我已經定義了一個用 clockwork 執行的 rake 任務,但是為了讓它在當前的開發環境中工作,我不得不使用 httparty 在內部調用它並使用接收到的 hash。`

  def rake_function
    @results = HTTParty.get("http://localhost:3000/controller/extension/")
    return @results.parsed_response
  end

In addition, my task makes a post and a put when the execution is finished and I must also use a httparty for that.

    if (!datExist)
        @response = HTTParty.post("http://localhost:3000/controller/extension/",
        body: eodData
        )
    else (datExist)
        checkId = dbData.select {|x| x["date_time"] == yesterday}
        id = checkId[0]["id"].to_s
        @response = HTTParty.put("http://localhost:3000/controller/extension/" + id,
        body: eodData
        )
    end

`

我知道這不是最佳方式,所以我希望能夠在我的 rake 任務中執行已經在我的控制器中定義的 function

你不知道。

controller 的唯一公共方法應該是 Rails 路由器在響應 HTTP 請求時調用的“操作”。

控制器是 Rack 應用程序,並且對傳入的 HTTP 請求有很強的依賴性——它們只是不像在 Rake 任務中那樣在該上下文之外工作,並且將您的控制器用作垃圾抽屜會導致“胖控制器”反模式。

控制器已經承擔了很多責任——它們基本上是通過將用戶輸入傳遞給模型並將模型傳遞給視圖來將您的整個應用程序拼接在一起。 不要給他們更多的工作要做。

這是一個很容易避免的問題,只需將您的 API 調用移至它們自己的 class 即可。設計此方法的一種方法是通過客戶端類,這些類僅負責與 API 進行通信:

class MyApiClient
  include HTTParty
  format :json
  base_url $baseurl # Code smell - avoid the use of globals
  attr_reader :api_key, :api_value

  def initalize(api_key:, api_value:)
    @api_key = api_key
    @api_value = api_value
  end

  def get_extension
    # I don't get why you think you need to dynamically set the header key
    self.class.get('extension', headers: { api_key => api_value })
  end
end

這使您可以簡單地重復使用 controller 和 rake 任務之間的代碼,並隔離接觸應用程序邊界的代碼,從而避免在您的應用程序和外部協作者之間建立緊密耦合。

當您實際將 HTTParty 用於面向 object 而不是過程代碼時,它也真的很閃耀。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM