Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Create a Custom Rake Task

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 246
    Comment on it

    Rake is a Ruby task management tool. Like in Unix we have 'make' utility.
    So we can say Rake is Ruby Make. It uses a Rakefile and .rake files to create a list of tasks.
    We can see all the Rake tasks available in our current directory by one of the below commands in terminal:

    rake --tasks
    rake -T


    Each task has a description, to help us finding the appropriate task.
    Let's create our own Custom rake take by using rake generator:

    $ rails g task my_rake


    It will generate scaffold for our new rake task: >lib/tasks/my_rake.rake
    open the file lib/tasks/my_rake.rake.It will look like this

    namespace :my_rake do
    
    end

    Here we have not described any task.Now we will create a new rake with task 'hello'.

    rails g task my_rake hello


    Now open the file lib/tasks/my_rake.rake.It will look like this

    namespace :my_rake do
    
      desc "TODO"
      task :hello => :environment do
      end
    
    end

    Here we have a task name hello. Now we can put our code here.

    namespace :my_rake do
    
      desc "Say hello"
      task hello: :environment do
          puts "Hello World!"
      end
    
      desc "Say how are you"
      task :ask => :hello do
       puts "How are you?"
      end
    
      desc "Say hello to random user in our model"
      task hello_user: :environment do
          puts "Hello #{choose(User).name}"
      end
    
      desc "Select random user"
      task :all => [:hello,:hello_user,:ask]
    
      def choose(model_class)
        model_class.find(:first)
      end
    
    end

    Here I have four tasks. Let's call each one of them.

    rake my_rake:hello
    output // Hello World!
    
    rake my_rake:ask
    output // Hello World!
            How are you?
    
    rake my_rake:hello_user
    output // Hello John!
            
    rake my_rake:all
    output // Hello World!
             Hello John!
             How are you?

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: