SlideShare a Scribd company logo
Exploring
Rake
Aug 2016 #rorosyd
@rudyyazdi
GitHub, Twitter, Medium, LinkedIn 👆
So what is Rake?
It’s a task runner.
It’s the official Ruby build tool.
As seen in:
rake db:migrate
rake db:schema:load
So what is the difference between
a task and a function?
Aren’t they both bunch of commands?
A quick detour to FP: side effects
def add(num1, num2)
logger.log("added #{num1} and #{num2}") # logging something
current_user.action_counter.up # say you are counting user’s actions
num1 + num2 # and store them in your database.
end
The first and second line are side effects because they modify something outside the
scope of the function. So this function is impure.
Result
focused
Side-
Effect
focused
Pure functions
Functions
Tasks
The syntax
Just put this in your Rakefile in the root of your project:
desc 'remove all files from build folder.'
task :clean do
Dir['build/*.*'].each { |file| File.delete(file) }
end
And then just run: $ rake clean
You can also store your .rake files in directory called rakelib or if you’re using
rails you can put them in lib/tasks directory
Namespacing
You can namespace your tasks:
namespace :asset do
desc 'remove all files from build folder.'
task :clean do
Dir['build/*.*'].each { |file| File.delete(file) }
end
end
And then just run: $ rake asset:clean
Appending a task
task :talk do
puts 'I am talking!'
end
task :talk do
puts 'Still talking!'
end
$ rake talk
I am talking!
Still talking!
Dependent tasks.
You can define dependency for each task.
task uglify: [:concat, :clean] do
# do stuff
end
:environment
If you’re using rails and want to load your entire app before a task just add
:environment as prerequisite:
task talk: :environment do
User.all.each { |u| u.notify("Happy new year!") }
end
Lets compare!!
Achieve these objectives:
1. Clear the build folder.
2. Concatenate all the files in .src.js .
3. Uglify the result.
4. Dump everything in a .min.js file.
5. Name the file the result of whoami command in the command line at the time of
build.
6. Put the file in the build folder.
There is more:
Access to previous tasks
You can invoke tasks from the other parts of your app:
task :talk do
Rake::Task['discussion:small_talk'].invoke
end
@already_invoked
task :first do
puts 'first task'
end
task second: :first do
puts 'first second'
end
task third: [:first, :second] do
puts 'first third'
end
$ rake third
first task
second task
third task
Enhance your tasks
Let’s say you want to notify a Slack channel if someone drops the database!!
Rake::Task["db:drop"].enhance do
slack_client.message("mayday, mayday, database dropped!")
end
Disclaimer: if someone is really planning to drop your db they’ll find a better way!
😈😈
Multitask
If you have a bunch of prerequisites that takes a long time:
multitask main_taks: [:long_task_1, :long_task_2, :long_task_3] do
# do stuff after all the above are finished (they will execute in parallel)
end
File tasks
This is for the tasks that generates the files:
file "rudy.min.js" do
# ...
end
FileList
files = Rake::FileList["**/*.md", "**/*.markdown"] # take all the matching files
files.exclude("~*") # exclude the ones beginning with ~
files.exclude(/^scratch//) # exclude the ones in the scratch folder
files.exclude do |f|
`git ls-files #{f}`.empty? # exclude the ones that are not tracked by git
end
files.each { |file| file.do_stuff }
* Shamelessly stolen from Avdi Grimm’s blog.
Rules
It matches your rake command with the provided regex and if it’s match it runs the
task.
rule '.html' do |t| # t here is the instance of task itself.
sh "touch #{t.name}"
end
$ rake fake.html
# creates an empty file called fake.html
Advanced rules
rule '.java' do |t|
puts t
end
rule '.class' => -> (tn) { tn.sub(/.class$/, '.java').sub(/^classes//, 'src/') } do |t|
puts t
end
$ rake classes/my.class
<Rake::FileTask src/my.java => []>
<Rake::FileTask classes/my.class => [src/my.java]>
Passing variables
task :sum, [:num1, :num2] do |_, args|
puts "the sum of #{args[:num1]} and #{args[:num2]}
is #{args[:num1].to_i + args[:num2].to_i}"
end
$ rake sum[2,7]
the sum of 2 and 7 is 9
Rake passes the task into the first block argument but since we’re not using it here
we replace it with “_”.
I know it’s kinda ugly so if you are working with too many variables checkout thor.
Thanks! 🤖🤖
Useful links:
Everything You Always Wanted to Know About Writing Good Rake Tasks * But
Were Afraid to Ask
Automated Tasks with Cron and Rake
Rake tutorial
Rake series by Avdi Grimm

More Related Content

What's hot

Where is my scalable api?
Where is my scalable api?Where is my scalable api?
Where is my scalable api?
Altoros
 
Reactive cocoa made Simple with Swift
Reactive cocoa made Simple with SwiftReactive cocoa made Simple with Swift
Reactive cocoa made Simple with Swift
Colin Eberhardt
 
Version control system & how to use git
Version control system & how to use git Version control system & how to use git
Version control system & how to use git
Ahmed Dalatony
 
Implementing a Backup Catalog… on a Student Budget
Implementing a Backup Catalog… on a Student BudgetImplementing a Backup Catalog… on a Student Budget
Implementing a Backup Catalog… on a Student Budget
Roy Zimmer
 
Sending email with send grid and laravel
Sending email with send grid and laravelSending email with send grid and laravel
Sending email with send grid and laravel
Sayed Ahmed
 
Intelligent infrastructure with SaltStack
Intelligent infrastructure with SaltStackIntelligent infrastructure with SaltStack
Intelligent infrastructure with SaltStack
Love Nyberg
 
2013 06-17-open-analytics
2013 06-17-open-analytics2013 06-17-open-analytics
2013 06-17-open-analyticsdrewr_
 
Reactive cocoa
Reactive cocoaReactive cocoa
Reactive cocoa
iacisclo
 
Essential Git and Github commands
Essential Git and Github commandsEssential Git and Github commands
Essential Git and Github commands
Isham Rashik
 
Introduction to Git for Artists
Introduction to Git for ArtistsIntroduction to Git for Artists
Introduction to Git for Artists
David Newbury
 
Error Handling in Swift
Error Handling in SwiftError Handling in Swift
Error Handling in Swift
Make School
 
Introduction to reactive programming & ReactiveCocoa
Introduction to reactive programming & ReactiveCocoaIntroduction to reactive programming & ReactiveCocoa
Introduction to reactive programming & ReactiveCocoa
Florent Pillet
 

What's hot (12)

Where is my scalable api?
Where is my scalable api?Where is my scalable api?
Where is my scalable api?
 
Reactive cocoa made Simple with Swift
Reactive cocoa made Simple with SwiftReactive cocoa made Simple with Swift
Reactive cocoa made Simple with Swift
 
Version control system & how to use git
Version control system & how to use git Version control system & how to use git
Version control system & how to use git
 
Implementing a Backup Catalog… on a Student Budget
Implementing a Backup Catalog… on a Student BudgetImplementing a Backup Catalog… on a Student Budget
Implementing a Backup Catalog… on a Student Budget
 
Sending email with send grid and laravel
Sending email with send grid and laravelSending email with send grid and laravel
Sending email with send grid and laravel
 
Intelligent infrastructure with SaltStack
Intelligent infrastructure with SaltStackIntelligent infrastructure with SaltStack
Intelligent infrastructure with SaltStack
 
2013 06-17-open-analytics
2013 06-17-open-analytics2013 06-17-open-analytics
2013 06-17-open-analytics
 
Reactive cocoa
Reactive cocoaReactive cocoa
Reactive cocoa
 
Essential Git and Github commands
Essential Git and Github commandsEssential Git and Github commands
Essential Git and Github commands
 
Introduction to Git for Artists
Introduction to Git for ArtistsIntroduction to Git for Artists
Introduction to Git for Artists
 
Error Handling in Swift
Error Handling in SwiftError Handling in Swift
Error Handling in Swift
 
Introduction to reactive programming & ReactiveCocoa
Introduction to reactive programming & ReactiveCocoaIntroduction to reactive programming & ReactiveCocoa
Introduction to reactive programming & ReactiveCocoa
 

Similar to Explore the Rake Gem

Introduction to RDoc
Introduction to RDocIntroduction to RDoc
Introduction to RDoc
Tim Lucas
 
Introduction to RDoc
Introduction to RDocIntroduction to RDoc
Introduction to RDoc
Tim Lucas
 
Gradle - small introduction
Gradle - small introductionGradle - small introduction
Gradle - small introductionIgor Popov
 
TorqueBox: The beauty of Ruby with the power of JBoss. Presented at Devnexus...
TorqueBox: The beauty of Ruby with the power of JBoss.  Presented at Devnexus...TorqueBox: The beauty of Ruby with the power of JBoss.  Presented at Devnexus...
TorqueBox: The beauty of Ruby with the power of JBoss. Presented at Devnexus...
bobmcwhirter
 
Ruby on Rails - Introduction
Ruby on Rails - IntroductionRuby on Rails - Introduction
Ruby on Rails - Introduction
Vagmi Mudumbai
 
Create a new project in ROR
Create a new project in RORCreate a new project in ROR
Create a new project in ROR
akankshita satapathy
 
Apache Cassandra and Apche Spark
Apache Cassandra and Apche SparkApache Cassandra and Apche Spark
Apache Cassandra and Apche Spark
Alex Thompson
 
Devtools cheatsheet
Devtools cheatsheetDevtools cheatsheet
Devtools cheatsheet
Dr. Volkan OBAN
 
Devtools cheatsheet
Devtools cheatsheetDevtools cheatsheet
Devtools cheatsheet
Dieudonne Nahigombeye
 
Toolbox of a Ruby Team
Toolbox of a Ruby TeamToolbox of a Ruby Team
Toolbox of a Ruby Team
Arto Artnik
 
PrizeExample.DS_Store__MACOSXPrizeExample._.DS_StoreP.docx
PrizeExample.DS_Store__MACOSXPrizeExample._.DS_StoreP.docxPrizeExample.DS_Store__MACOSXPrizeExample._.DS_StoreP.docx
PrizeExample.DS_Store__MACOSXPrizeExample._.DS_StoreP.docx
ChantellPantoja184
 
How to start using Scala
How to start using ScalaHow to start using Scala
How to start using ScalaNgoc Dao
 
Presentation laravel 5 4
Presentation laravel 5 4Presentation laravel 5 4
Presentation laravel 5 4
Christen Gjølbye Christensen
 
Android presentation - Gradle ++
Android presentation - Gradle ++Android presentation - Gradle ++
Android presentation - Gradle ++
Javier de Pedro López
 
Buildr In Action @devoxx france 2012
Buildr In Action @devoxx france 2012Buildr In Action @devoxx france 2012
Buildr In Action @devoxx france 2012
alexismidon
 
A tour on ruby and friends
A tour on ruby and friendsA tour on ruby and friends
A tour on ruby and friends旻琦 潘
 
Basic Gradle Plugin Writing
Basic Gradle Plugin WritingBasic Gradle Plugin Writing
Basic Gradle Plugin Writing
Schalk Cronjé
 
To Batch Or Not To Batch
To Batch Or Not To BatchTo Batch Or Not To Batch
To Batch Or Not To Batch
Luca Mearelli
 
Demystifying Maven
Demystifying MavenDemystifying Maven
Demystifying Maven
Mike Desjardins
 

Similar to Explore the Rake Gem (20)

Introduction to RDoc
Introduction to RDocIntroduction to RDoc
Introduction to RDoc
 
Introduction to RDoc
Introduction to RDocIntroduction to RDoc
Introduction to RDoc
 
Gradle - small introduction
Gradle - small introductionGradle - small introduction
Gradle - small introduction
 
TorqueBox: The beauty of Ruby with the power of JBoss. Presented at Devnexus...
TorqueBox: The beauty of Ruby with the power of JBoss.  Presented at Devnexus...TorqueBox: The beauty of Ruby with the power of JBoss.  Presented at Devnexus...
TorqueBox: The beauty of Ruby with the power of JBoss. Presented at Devnexus...
 
Ruby on Rails - Introduction
Ruby on Rails - IntroductionRuby on Rails - Introduction
Ruby on Rails - Introduction
 
Grunt.js introduction
Grunt.js introductionGrunt.js introduction
Grunt.js introduction
 
Create a new project in ROR
Create a new project in RORCreate a new project in ROR
Create a new project in ROR
 
Apache Cassandra and Apche Spark
Apache Cassandra and Apche SparkApache Cassandra and Apche Spark
Apache Cassandra and Apche Spark
 
Devtools cheatsheet
Devtools cheatsheetDevtools cheatsheet
Devtools cheatsheet
 
Devtools cheatsheet
Devtools cheatsheetDevtools cheatsheet
Devtools cheatsheet
 
Toolbox of a Ruby Team
Toolbox of a Ruby TeamToolbox of a Ruby Team
Toolbox of a Ruby Team
 
PrizeExample.DS_Store__MACOSXPrizeExample._.DS_StoreP.docx
PrizeExample.DS_Store__MACOSXPrizeExample._.DS_StoreP.docxPrizeExample.DS_Store__MACOSXPrizeExample._.DS_StoreP.docx
PrizeExample.DS_Store__MACOSXPrizeExample._.DS_StoreP.docx
 
How to start using Scala
How to start using ScalaHow to start using Scala
How to start using Scala
 
Presentation laravel 5 4
Presentation laravel 5 4Presentation laravel 5 4
Presentation laravel 5 4
 
Android presentation - Gradle ++
Android presentation - Gradle ++Android presentation - Gradle ++
Android presentation - Gradle ++
 
Buildr In Action @devoxx france 2012
Buildr In Action @devoxx france 2012Buildr In Action @devoxx france 2012
Buildr In Action @devoxx france 2012
 
A tour on ruby and friends
A tour on ruby and friendsA tour on ruby and friends
A tour on ruby and friends
 
Basic Gradle Plugin Writing
Basic Gradle Plugin WritingBasic Gradle Plugin Writing
Basic Gradle Plugin Writing
 
To Batch Or Not To Batch
To Batch Or Not To BatchTo Batch Or Not To Batch
To Batch Or Not To Batch
 
Demystifying Maven
Demystifying MavenDemystifying Maven
Demystifying Maven
 

Recently uploaded

GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
Alina Yurenko
 
openEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain SecurityopenEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain Security
Shane Coughlan
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
Philip Schwarz
 
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdfVitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke
 
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket ManagementUtilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate
 
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
Łukasz Chruściel
 
GraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph TechnologyGraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph Technology
Neo4j
 
What is Augmented Reality Image Tracking
What is Augmented Reality Image TrackingWhat is Augmented Reality Image Tracking
What is Augmented Reality Image Tracking
pavan998932
 
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdfAutomated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
timtebeek1
 
Empowering Growth with Best Software Development Company in Noida - Deuglo
Empowering Growth with Best Software  Development Company in Noida - DeugloEmpowering Growth with Best Software  Development Company in Noida - Deuglo
Empowering Growth with Best Software Development Company in Noida - Deuglo
Deuglo Infosystem Pvt Ltd
 
Graspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code AnalysisGraspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code Analysis
Aftab Hussain
 
Using Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional SafetyUsing Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional Safety
Ayan Halder
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
Max Andersen
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
Paco van Beckhoven
 
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
mz5nrf0n
 
Launch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in MinutesLaunch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in Minutes
Roshan Dwivedi
 
Transform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR SolutionsTransform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR Solutions
TheSMSPoint
 
Artificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension FunctionsArtificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension Functions
Octavian Nadolu
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
Fermin Galan
 
Fundamentals of Programming and Language Processors
Fundamentals of Programming and Language ProcessorsFundamentals of Programming and Language Processors
Fundamentals of Programming and Language Processors
Rakesh Kumar R
 

Recently uploaded (20)

GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
 
openEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain SecurityopenEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain Security
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
 
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdfVitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdf
 
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket ManagementUtilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
 
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
 
GraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph TechnologyGraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph Technology
 
What is Augmented Reality Image Tracking
What is Augmented Reality Image TrackingWhat is Augmented Reality Image Tracking
What is Augmented Reality Image Tracking
 
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdfAutomated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
 
Empowering Growth with Best Software Development Company in Noida - Deuglo
Empowering Growth with Best Software  Development Company in Noida - DeugloEmpowering Growth with Best Software  Development Company in Noida - Deuglo
Empowering Growth with Best Software Development Company in Noida - Deuglo
 
Graspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code AnalysisGraspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code Analysis
 
Using Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional SafetyUsing Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional Safety
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
 
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
 
Launch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in MinutesLaunch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in Minutes
 
Transform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR SolutionsTransform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR Solutions
 
Artificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension FunctionsArtificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension Functions
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
 
Fundamentals of Programming and Language Processors
Fundamentals of Programming and Language ProcessorsFundamentals of Programming and Language Processors
Fundamentals of Programming and Language Processors
 

Explore the Rake Gem

  • 3. So what is Rake? It’s a task runner. It’s the official Ruby build tool. As seen in: rake db:migrate rake db:schema:load
  • 4. So what is the difference between a task and a function? Aren’t they both bunch of commands?
  • 5. A quick detour to FP: side effects def add(num1, num2) logger.log("added #{num1} and #{num2}") # logging something current_user.action_counter.up # say you are counting user’s actions num1 + num2 # and store them in your database. end The first and second line are side effects because they modify something outside the scope of the function. So this function is impure.
  • 7. The syntax Just put this in your Rakefile in the root of your project: desc 'remove all files from build folder.' task :clean do Dir['build/*.*'].each { |file| File.delete(file) } end And then just run: $ rake clean You can also store your .rake files in directory called rakelib or if you’re using rails you can put them in lib/tasks directory
  • 8. Namespacing You can namespace your tasks: namespace :asset do desc 'remove all files from build folder.' task :clean do Dir['build/*.*'].each { |file| File.delete(file) } end end And then just run: $ rake asset:clean
  • 9. Appending a task task :talk do puts 'I am talking!' end task :talk do puts 'Still talking!' end $ rake talk I am talking! Still talking!
  • 10. Dependent tasks. You can define dependency for each task. task uglify: [:concat, :clean] do # do stuff end
  • 11. :environment If you’re using rails and want to load your entire app before a task just add :environment as prerequisite: task talk: :environment do User.all.each { |u| u.notify("Happy new year!") } end
  • 13. Achieve these objectives: 1. Clear the build folder. 2. Concatenate all the files in .src.js . 3. Uglify the result. 4. Dump everything in a .min.js file. 5. Name the file the result of whoami command in the command line at the time of build. 6. Put the file in the build folder.
  • 15. Access to previous tasks You can invoke tasks from the other parts of your app: task :talk do Rake::Task['discussion:small_talk'].invoke end
  • 16. @already_invoked task :first do puts 'first task' end task second: :first do puts 'first second' end task third: [:first, :second] do puts 'first third' end $ rake third first task second task third task
  • 17. Enhance your tasks Let’s say you want to notify a Slack channel if someone drops the database!! Rake::Task["db:drop"].enhance do slack_client.message("mayday, mayday, database dropped!") end Disclaimer: if someone is really planning to drop your db they’ll find a better way! 😈😈
  • 18. Multitask If you have a bunch of prerequisites that takes a long time: multitask main_taks: [:long_task_1, :long_task_2, :long_task_3] do # do stuff after all the above are finished (they will execute in parallel) end
  • 19. File tasks This is for the tasks that generates the files: file "rudy.min.js" do # ... end
  • 20. FileList files = Rake::FileList["**/*.md", "**/*.markdown"] # take all the matching files files.exclude("~*") # exclude the ones beginning with ~ files.exclude(/^scratch//) # exclude the ones in the scratch folder files.exclude do |f| `git ls-files #{f}`.empty? # exclude the ones that are not tracked by git end files.each { |file| file.do_stuff } * Shamelessly stolen from Avdi Grimm’s blog.
  • 21. Rules It matches your rake command with the provided regex and if it’s match it runs the task. rule '.html' do |t| # t here is the instance of task itself. sh "touch #{t.name}" end $ rake fake.html # creates an empty file called fake.html
  • 22. Advanced rules rule '.java' do |t| puts t end rule '.class' => -> (tn) { tn.sub(/.class$/, '.java').sub(/^classes//, 'src/') } do |t| puts t end $ rake classes/my.class <Rake::FileTask src/my.java => []> <Rake::FileTask classes/my.class => [src/my.java]>
  • 23. Passing variables task :sum, [:num1, :num2] do |_, args| puts "the sum of #{args[:num1]} and #{args[:num2]} is #{args[:num1].to_i + args[:num2].to_i}" end $ rake sum[2,7] the sum of 2 and 7 is 9 Rake passes the task into the first block argument but since we’re not using it here we replace it with “_”. I know it’s kinda ugly so if you are working with too many variables checkout thor.
  • 25. Useful links: Everything You Always Wanted to Know About Writing Good Rake Tasks * But Were Afraid to Ask Automated Tasks with Cron and Rake Rake tutorial Rake series by Avdi Grimm