Rails:运行 来自代码的控制器操作
Rails: Run a controller action from code
我想在我的 Rails 应用程序中自动执行一项任务,创建一个 rake 任务,我需要的几乎所有代码都在控制器操作中,我只想调用该控制器操作而不是编写我任务中的 "same" 代码并保存一些代码行。这可能吗?
嗯,举个例子。假设您有用例从 Rake 任务和使用客户端自动续订 Stripe 客户订阅。现在,您将编写如下所示的 PORO class:
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
您可以将 class 放在 app/services/auto_renew_subscription.rb
文件夹中。现在这个 class 在全球范围内可用。因此,在控制器内部调用它,如:
class SubscriptionController < ApplicationController
def create
#.. some logic
AutoRenewSubscription.new(
coupon: "VXTYRE", email: 'some@email.com'
).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: 'some@email.com'
).run!
end
这是我认为解决您问题的好方法。希望你会喜欢我的想法。 :)
我想在我的 Rails 应用程序中自动执行一项任务,创建一个 rake 任务,我需要的几乎所有代码都在控制器操作中,我只想调用该控制器操作而不是编写我任务中的 "same" 代码并保存一些代码行。这可能吗?
嗯,举个例子。假设您有用例从 Rake 任务和使用客户端自动续订 Stripe 客户订阅。现在,您将编写如下所示的 PORO class:
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
您可以将 class 放在 app/services/auto_renew_subscription.rb
文件夹中。现在这个 class 在全球范围内可用。因此,在控制器内部调用它,如:
class SubscriptionController < ApplicationController
def create
#.. some logic
AutoRenewSubscription.new(
coupon: "VXTYRE", email: 'some@email.com'
).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: 'some@email.com'
).run!
end
这是我认为解决您问题的好方法。希望你会喜欢我的想法。 :)