2016-08-01 52 views
0

我想在Rails應用程序中自動執行一項任務,創建一個Rake任務,幾乎所有我需要的代碼都是在控制器動作中,我想只是調用該控制器動作在我的任務中寫入「相同」代碼並保存一些代碼行。那可能嗎?例如,Rails:從代碼運行控制器動作

+1

沒有那是一個糟糕的設計。正確的方法是創建一個PORO類,然後使用該類在控制器和Rake任務中執行邏輯。這樣您就可以堅持DRY。 –

+0

如果您有任何鏈接,或者您認識的資源會有所幫助,請將它們添加到答案中,我會將答案標記爲已接受,謝謝=) – SsouLlesS

回答

0

那麼,假設您有用於從Rake任務和客戶端自動續訂Stripe客戶訂閱。現在,你會寫一個PORO類象下面這樣:

class AutoRenewSubscription 
    attr_reader :coupon, :email 

    def initialize args = {} 
    @email = args[:email] 
    @coupon = args[:coupon] 
    #.... 
    end 

    def run! 
    user_current_plan.toggle!(:auto_renew) 

    case action 
    when :resume 
     resume_subscription 
    when :cancel 
     cancel_subscription 
    end 
    end 
    #... some more code as you need. 
end 

你可以把類app/services/auto_renew_subscription.rb文件夾內。現在這個課程在全球範圍內提供所以,這樣稱呼它的控制器內:

class SubscriptionController < ApplicationController 
    def create 
    #.. some logic 
    AutoRenewSubscription.new(
    coupon: "VXTYRE", email: '[email protected]' 
    ).run! 
    end 
end 

而且還從你的rake任務就調用它:

desc "This task is to auto renew user subscriptions" 
task :auto_renew => :environment do 
    puts "auto renew." 
    AutoRenewSubscription.new(
    coupon: "VXTYRE", email: '[email protected]' 
).run! 
end 

這是我認爲解決您的問題好辦法。希望你會喜歡我的想法。 :)