Ruby rake: Difference between revisions

From wikinotes
 
Line 91: Line 91:
</source>
</source>
</blockquote><!-- basics -->
</blockquote><!-- basics -->
= Tricks =
<blockquote>
== Rails ==
<blockquote>
You can eager load a rails application by specifying the environment.
<source lang="ruby">
# {project}/Rakefile
namespace :foo do
  task bar: [:environment] do
    puts MyModel.first
  end
end
</source>
</blockquote><!-- rails -->
</blockquote><!-- tricks -->

Revision as of 17:21, 2 May 2023

rake is a make like tool for ruby.

Documentation

official docs https://ruby.github.io/rake/index.html

Tutorials

intro video https://www.youtube.com/watch?v=AFPWDzHWjEY

Locations

project/
  rakelib/            # like conf.d, read as if in rakefile
      tags.rake
      test.rake
  lib/tasks/          # [rails only] same as rakelib
      content.rake
      db.rake
  Rakefile            # toplevel file

Usage

rake -T                  # list all rake tasks
rake -T <word>           # list rake tasks that contain '<word>'
rake -P                  # list all rake tasks, with their dependencies
rake <taskname>          # run task
rake <taskname> VAR=foo  # set environment variable within task

Basics

Rakefiles are conceptually similar to Makefiles.

  • Rakefiles are composed of tasks
  • Tasks can have dependencies on other tasks.
# {project}/Rakefile

# set default task, run when 'rake' invoked with no args
task :default => :mac_and_cheese

# task with dependencies
desc "Make some tasty mac & cheese"
task :mac_and_cheese => [:boil_water, :buy_pasta, :buy_cheese] do
  puts "Making mac and cheese"
end

namespace :store do
  desc "go to store"
  task :go_to_store
    puts "going to store"
  end

  desc "buy some cheese"
  task :buy_cheese
    puts "buying cheese"
  end

  desc "buy some pasta"
  task :buy_pasta
    puts "buying pasta"
  end
end

task :boil_water => [:buy_pasta, :buy_cheese]
  puts "boiling water"
end
rake                     # runs :default task
rake mac_and_cheese      # runs :mac_and_cheese
rake store:buy_cheese    # runs :buy_cheese from namespace :store

Tricks

Rails

You can eager load a rails application by specifying the environment.

# {project}/Rakefile

namespace :foo do
  task bar: [:environment] do
    puts MyModel.first
  end
end