Search code examples
ruby-on-railsruby-on-rails-4rakerake-task

Rails: Run a controller action from code


I would like to automate a task in my Rails app, create a rake task, almost all the code I need is in a controller action, I would like to just call that controller action instead of write the "same" code in my task and save some lines of code. Is that possible?


Solution

  • Well, for example. Say you have usecase to auto renew Stripe customers subscriptions from both Rake tasks and using client side . Now, you will write a PORO class like below:

    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
    

    You can put the class inside app/services/auto_renew_subscription.rb folder. Now this class is available globally. So, call it inside the controller like :

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

    And do call it from your rake task also :

    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
    

    This is what I think good way to solve your issue. Hope you will like my idea. :)