### Install Dependencies and Run Rake Test Suite Source: https://github.com/ruby/rake/blob/master/CONTRIBUTING.rdoc This snippet demonstrates how to set up development dependencies using bundler and then execute the Rake test suite. It assumes you are in the top project directory of Rake. ```bash #!/bin/bash cd /path/to/rake/project bin/setup rake ``` -------------------------------- ### Common Rake Command Line Usage Examples Source: https://context7.com/ruby/rake/llms.txt Provides a comprehensive set of command-line examples for interacting with Rake. Covers running default and specific tasks, tasks with arguments, multiple tasks, listing tasks, controlling execution (dry run, trace, quiet), parallel execution, passing environment variables, and using different Rakefiles. ```bash # Run default task rake # Run specific task rake build # Run task with arguments rake deploy[production] rake "greet[John Doe, Hello]" # Run multiple tasks rake clean build test # List available tasks rake -T # Tasks with descriptions rake -T deploy # Filter by pattern rake -D # Full descriptions rake -W # Show task locations rake -P # Show prerequisites # Control execution rake -n # Dry run (show what would happen) rake -t # Trace execution rake --trace=stdout # Trace to stdout rake -q # Quiet mode rake -s # Silent mode # Parallel execution rake -j4 build # Use 4 threads max rake -m build # Run all tasks as multitasks # Pass environment variables rake build RAILS_ENV=production rake deploy VERSION=1.2.3 # Use different rakefile rake -f other_rakefile.rb rake -R lib/tasks # Use different rakelib directory # System-wide rakefiles rake -g # Use global rakefiles rake -G # Ignore global rakefiles ``` -------------------------------- ### Define basic Rake tasks Source: https://github.com/ruby/rake/blob/master/doc/rational.rdoc Demonstrates how to define a simple task using a symbol and how to execute shell commands using the FileUtils module. This example shows a 'clean' task that removes backup files. ```ruby task :clean do Dir['*~'].each {|fn| rm fn rescue nil} end ``` -------------------------------- ### Define file-based build dependencies Source: https://github.com/ruby/rake/blob/master/doc/rational.rdoc Illustrates how to use the 'file' command to define build rules based on file existence and modification timestamps. This example compiles a C++ source file into an object file. ```ruby file "hello.cc" file "hello.o" => ["hello.cc"] do |t| srcfile = t.name.sub(/\.o$/, ".cc") sh %{g++ #{srcfile} -c -o #{t.name}} end ``` -------------------------------- ### Rakefile Task Examples Source: https://github.com/ruby/rake/blob/master/doc/rakefile.rdoc Common Rake tasks for managing an application, including installation, code analysis, documentation generation, and testing. These tasks are executed from the command line. ```ruby task :install task :lines task :rdoc task :rerdoc task :test task :testall ``` -------------------------------- ### Rake Task Manipulation API Source: https://context7.com/ruby/rake/llms.txt Provides examples of programmatically accessing and manipulating Rake tasks at runtime using Rake's Task API. This includes defining basic tasks and demonstrating how they can be referenced and potentially modified. ```ruby # Rakefile task :setup do puts "Setting up..." end task :build do puts "Building..." end task :test do puts "Testing..." end ``` -------------------------------- ### Define Basic Tasks with Rake Source: https://context7.com/ruby/rake/llms.txt Demonstrates how to declare tasks with prerequisites, arguments, and default behaviors using the task DSL method. ```ruby task :hello do puts "Hello, World!" end task greet: [:hello] do puts "Greetings complete!" end task default: %w[test lint build] task :greet_user, [:name, :greeting] do |t, args| args.with_defaults(name: "User", greeting: "Hello") puts "#{args.greeting}, #{args.name}!" end task :deploy, [:env] => [:test, :build] do |t, args| puts "Deploying to #{args.env || 'production'}..." end ``` -------------------------------- ### Rake Task Declaration with Namespaces (Ruby) Source: https://github.com/ruby/rake/blob/master/History.rdoc This enhancement allows Rake tasks to be declared under a namespace, improving organization for larger projects. For example, 'a:b' defines a task 'b' within the namespace 'a'. Introduced in version 10.2.0. ```Ruby namespace :web do task :deploy do puts "Deploying web application..." end end task 'a:b' do puts "Task a:b executed" end ``` -------------------------------- ### Initialize a Custom Rake Application Source: https://github.com/ruby/rake/blob/master/History.rdoc Shows the pattern for initializing a custom Rake application instance using Rake.application.init and top_level methods. ```ruby gem 'rake', ">= 0.7.3" require 'rake' Rake.application.init('myrake') task :default do something_interesting end Rake.application.top_level ``` -------------------------------- ### Organize Tasks with Namespaces Source: https://context7.com/ruby/rake/llms.txt Demonstrates grouping related tasks into namespaces to prevent naming collisions and improve project structure. ```ruby namespace :db do desc "Create the database" task :create do puts "Creating database..." end task migrate: [:create] do puts "Running migrations..." end namespace :test do task prepare: ["db:create"] do puts "Preparing test database..." end end end task deploy: ["db:migrate", "assets:compile"] ``` -------------------------------- ### Compiling C Source Files with Rake (Ruby) Source: https://github.com/ruby/rake/blob/master/doc/rational.rdoc This snippet demonstrates how Rake can be used to automate the compilation of C source files. It utilizes a hypothetical `c_source_file` function to generate compilation tasks for all files ending in '.c' within the current directory. This showcases Rake's extensibility for build automation. ```ruby require 'rake/ctools' Dir['*.c'].each do |fn| c_source_file(fn) end ``` -------------------------------- ### Create Directory Tasks Source: https://context7.com/ruby/rake/llms.txt Illustrates the use of the directory method to ensure required directory structures exist, including automatic parent directory creation. ```ruby directory "tmp" directory "build/output/reports" directory "dist" file "dist/app.js" => ["dist", "src/app.js"] do |t| cp "src/app.js", t.name end directory "logs" file "logs" do chmod 0755, "logs" end ``` -------------------------------- ### Create Distribution Archives with Rake::PackageTask Source: https://context7.com/ruby/rake/llms.txt Automates the creation of distributable package files (tar.gz, tar.bz2, zip) using `Rake::PackageTask`. It allows specifying package name, version, output directory, and the files to include or exclude. ```ruby # Rakefile require 'rake/packagetask' Rake::PackageTask.new('myproject', '1.0.0') do |p| p.need_tar_gz = true p.need_tar_bz2 = true p.need_zip = true p.package_dir = 'pkg' p.package_files.include('lib/**/*.rb') p.package_files.include('bin/*') p.package_files.include('README.md', 'LICENSE', 'CHANGELOG.md') p.package_files.include('Rakefile') p.package_files.exclude('**/*.bak') p.package_files.exclude('**/.*') end # Creates tasks: # rake package # Build all packages # rake repackage # Force rebuild # rake clobber_package # Remove packages # Output files in pkg/: # pkg/myproject-1.0.0.tar.gz # pkg/myproject-1.0.0.tar.bz2 # pkg/myproject-1.0.0.zip ``` -------------------------------- ### Execute Parallel Tasks with Multitask Source: https://context7.com/ruby/rake/llms.txt Explains how to use the multitask method to run task prerequisites concurrently, significantly reducing build times for independent operations. ```ruby task :fetch_users do sleep 2 puts "Users fetched" end task :fetch_products do sleep 2 puts "Products fetched" end task :fetch_orders do sleep 2 puts "Orders fetched" end multitask fetch_all: [:fetch_users, :fetch_products, :fetch_orders] do puts "All data fetched!" end ``` -------------------------------- ### Create and Manipulate FileLists in Rake Source: https://context7.com/ruby/rake/llms.txt Demonstrates the creation and manipulation of `FileList` objects, which are optimized for working with file names and glob patterns. It covers creating lists from patterns, customizing with blocks, adding/excluding files, and transforming file names and paths. ```ruby # Rakefile # Create FileList with glob patterns source_files = FileList['src/**/*.rb', 'lib/**/*.rb'] test_files = FileList['test/**/test_*.rb'] # Create with block for customization package_files = FileList.new('lib/**/*') do |fl| fl.exclude(/\.bak$/) fl.exclude(/~$/) fl.exclude(/CVS/) end # Add and exclude files files = FileList['**/*.rb'] files.include('extra/**/*.rb') files.exclude('vendor/**/*') files.exclude { |f| File.directory?(f) } # FileList operations puts source_files.to_a # Convert to array puts source_files.join(':') # Join with separator puts source_files.length # Count files # Transform file names object_files = source_files.ext('.o') # Change extension output_files = source_files.pathmap('%{src,build}p') # Transform paths modified = source_files.sub(/^src/, 'lib') # String substitution modified = source_files.gsub(/test/, 'spec') # Global substitution # Filter existing files only existing = FileList['**/*.rb'].existing # Search within files FileList['**/*.rb'].egrep(/TODO|FIXME/) do |file, line_num, line| puts "#{file}:#{line_num}: #{line.strip}" end ``` -------------------------------- ### Access and Manipulate Rake Tasks Source: https://context7.com/ruby/rake/llms.txt Demonstrates how to access existing Rake tasks by name, inspect their properties (name, prerequisites, actions), check for task definition, dynamically add prerequisites and actions, clear and redefine tasks, and invoke tasks. It also shows how to list all defined tasks. ```ruby # Access a task by name task :manipulate do build_task = Rake::Task[:build] # Inspect task properties puts build_task.name # => "build" puts build_task.prerequisites.inspect # => [] puts build_task.actions.length # => 1 # Check if task exists puts Rake::Task.task_defined?(:build) # => true # Add prerequisites dynamically build_task.enhance([:setup]) # Add actions dynamically build_task.enhance do puts "Additional build step!" end # Clear and redefine test_task = Rake::Task[:test] test_task.clear_prerequisites test_task.clear_actions test_task.enhance([:build]) do puts "New test implementation" end # Re-enable a task (allow it to run again) build_task.invoke build_task.reenable build_task.invoke # Runs again # List all defined tasks Rake::Task.tasks.each do |t| puts "#{t.name}: #{t.comment}" end end # Invoke tasks programmatically task :deploy do Rake::Task[:build].invoke Rake::Task[:test].invoke puts "Deploying..." end ``` -------------------------------- ### Define tasks with dependencies Source: https://github.com/ruby/rake/blob/master/doc/rational.rdoc Shows how to create a task that depends on another task. The 'clobber' task is configured to run only after the 'clean' task has completed. ```ruby task :clobber => [:clean] do rm_r "tempdir" end ``` -------------------------------- ### Rakefile Dynamic Dependency Loading with Makefile Loader Source: https://context7.com/ruby/rake/llms.txt Illustrates dynamic dependency loading in Rake using the `makefile` loader. It defines rules to generate dependency files (`.d`) from C source files and imports these dependencies before task execution. ```ruby # Rakefile require 'rake/loaders/makefile' SOURCES = FileList['src/**/*.c'] DEPFILES = SOURCES.ext('.d') # Generate dependency files rule '.d' => '.c' do |t| sh "gcc -MM -MF #{t.name} #{t.source}" end # Import dependencies after generating them import(*DEPFILES) # Alternative: generate all deps at once file '.depends.mf' => SOURCES do |t| sh "makedepend -f- -- #{SOURCES} > #{t.name}" end import '.depends.mf' # Import other rake files import 'tasks/database.rake' import 'tasks/deploy.rake' import Dir['lib/tasks/**/*.rake'] ``` -------------------------------- ### Rake Pathmap Transformations Source: https://context7.com/ruby/rake/llms.txt Explains and demonstrates the `pathmap` method for powerful path transformations within `FileList` objects. It covers various specifiers for extracting parts of a path and combining them, as well as directory substitution and usage in build rules. ```ruby # Rakefile files = FileList['src/app/models/user.rb', 'src/app/controllers/users_controller.rb'] # Pathmap specifiers: # %p - full path # %f - file name with extension # %n - file name without extension # %d - directory # %x - extension # %X - everything but extension files.pathmap('%f') # => ['user.rb', 'users_controller.rb'] files.pathmap('%n') # => ['user', 'users_controller'] files.pathmap('%d') # => ['src/app/models', 'src/app/controllers'] files.pathmap('%x') # => ['.rb', '.rb'] # Combine specifiers files.pathmap('%d/%n.o') # => ['src/app/models/user.o', ...] # Directory substitution files.pathmap('%{src,build}p') # Replace 'src' with 'build' in path # Use in build rules SOURCES = FileList['src/**/*.c'] OBJECTS = SOURCES.pathmap('%{src,build}X.o') task build: OBJECTS rule '.o' => [proc { |t| t.pathmap('%{build,src}X.c') }] do |t| mkdir_p File.dirname(t.name) sh "gcc -c -o #{t.name} #{t.source}" end ``` -------------------------------- ### Define Rake Tasks with Prerequisites and Actions Source: https://github.com/ruby/rake/blob/master/doc/rakefile.rdoc Demonstrates how to define tasks using symbols or strings, assign prerequisites, and execute blocks of Ruby code. It covers simple tasks, tasks with dependencies, and adding actions to tasks. ```ruby task :name task name: [:prereq1, :prereq2] task 'name' => %w[prereq1 prereq2] task name: [:prereq1, :prereq2] do |t| # actions (may reference t) end ``` -------------------------------- ### Define File Tasks Source: https://github.com/ruby/rake/blob/master/doc/rakefile.rdoc Shows how to use the file method to create tasks that generate files. These tasks are typically skipped if the target file already exists. ```ruby file "prog" => ["a.o", "b.o"] do |t| sh "cc -o #{t.name} #{t.prerequisites.join(' ')}" end ``` -------------------------------- ### Rake FileList Creation Source: https://github.com/ruby/rake/blob/master/doc/rakefile.rdoc Shows how to create FileLists in Rake, which are used to manage collections of files. FileLists can be initialized with explicit file names or glob patterns. ```ruby fl = FileList['file1.rb', file2.rb'] fl = FileList['*.rb'] ``` -------------------------------- ### Define Rakefile Tasks and Dependencies (Ruby) Source: https://github.com/ruby/rake/blob/master/README.rdoc This snippet demonstrates how to define tasks and their dependencies within a Rakefile using Ruby syntax. It shows a 'test' task that executes a Ruby script and a 'default' task that depends on the 'test' task. ```ruby task default: %w[test] task :test do ruby "test/unittest.rb" end ``` -------------------------------- ### Define and Execute Tasks in Ruby Source: https://github.com/ruby/rake/blob/master/doc/proto_rake.rdoc This snippet implements the core Task and FileTask classes, providing mechanisms to define tasks with dependencies and execute them. It includes logic for checking file modification times to determine if a task needs to be re-run. ```ruby #!/usr/bin/env ruby require 'ftools' class Task TASKS = Hash.new attr_reader :prerequisites def initialize(task_name) @name = task_name @prerequisites = [] @actions = [] end def enhance(deps=nil, &block) @prerequisites |= deps if deps @actions << block if block_given? self end def invoke @prerequisites.each { |n| Task[n].invoke } execute if needed? end def execute return if @triggered @triggered = true @actions.collect { |act| result = act.call(self) }.last end def needed? true end def timestamp Time.now end class << self def [](task_name) TASKS[intern(task_name)] or fail "Don't know how to rake #{task_name}" end def define_task(args, &block) case args when Hash fail "Too Many Target Names: #{args.keys.join(' ')}" if args.size > 1 fail "No Task Name Given" if args.size < 1 task_name = args.keys[0] deps = args[task_name] else task_name = args deps = [] end deps = deps.collect {|d| intern(d) } get(task_name).enhance(deps, &block) end def get(task_name) name = intern(task_name) TASKS[name] ||= self.new(name) end def intern(task_name) (Symbol === task_name) ? task_name : task_name.intern end end end class FileTask < Task def needed? return true unless File.exist?(name) latest_prereq = @prerequisites.collect{|n| Task[n].timestamp}.max return false if latest_prereq.nil? timestamp < latest_prereq end def timestamp File.new(name.to_s).mtime end end ``` -------------------------------- ### Define File Tasks in Rake Source: https://context7.com/ruby/rake/llms.txt Shows how to create file-based tasks that only execute if the target file is missing or outdated relative to its prerequisites. ```ruby file "main.o" => ["main.c", "header.h"] do |t| sh "gcc -c -o #{t.name} main.c" end file "myapp" => ["main.o", "utils.o"] do |t| sh "gcc -o #{t.name} #{t.prerequisites.join(' ')}" end file "config.yml" => ["config.yml.template"] do |t| require 'erb' template = File.read(t.prerequisites.first) result = ERB.new(template).result(binding) File.write(t.name, result) end task build: ["myapp"] ``` -------------------------------- ### Describe Rake Tasks Source: https://github.com/ruby/rake/blob/master/doc/rakefile.rdoc Uses the desc command to provide documentation for tasks, which is then displayed when running rake -T. ```ruby desc "Create a distribution package" task package: %w[ ... ] do ... end ``` -------------------------------- ### Execute Parallel Tasks Source: https://github.com/ruby/rake/blob/master/doc/rakefile.rdoc Demonstrates the use of multitask to execute prerequisites in parallel using Ruby threads for improved performance. ```ruby multitask copy_files: %w[copy_src copy_doc copy_bin] do puts "All Copies Complete" end ``` -------------------------------- ### Configure Test Runner with Rake::TestTask Source: https://context7.com/ruby/rake/llms.txt Sets up Rake tasks for running test suites using `Rake::TestTask`. It allows configuration of library paths, test file patterns, verbosity, and command-line options for running specific tests or configurations. ```ruby # Rakefile require 'rake/testtask' # Basic test task Rake::TestTask.new do |t| t.libs << 'test' t.libs << 'lib' t.test_files = FileList['test/**/*_test.rb'] t.verbose = true end # Named test task with prerequisites Rake::TestTask.new(test_unit: [:compile]) do |t| t.libs = ['lib', 'test'] t.pattern = 'test/unit/**/*_test.rb' t.warning = true t.verbose = true end # Integration tests Rake::TestTask.new(:test_integration) do |t| t.libs << 'test' t.test_files = FileList['test/integration/**/*_test.rb'] t.verbose = true t.ruby_opts = ['-r', 'rubygems'] end # Run specific tests from command line: # rake test # Run all tests # rake test TEST=test/foo_test.rb # Run single file # rake test TESTOPTS="-v" # Verbose output # rake test TESTOPTS="--name=test_something" # Run specific test ``` -------------------------------- ### Define Rake Rules for File Synthesis Source: https://github.com/ruby/rake/blob/master/doc/rakefile.rdoc Shows how to define rules to automatically synthesize tasks for files based on extensions or complex patterns using regex and procs. ```ruby rule '.o' => ['.c'] do |t| sh "cc #{t.source} -c -o #{t.name}" end rule( /\.o$/ => [ proc {|task_name| task_name.sub(/\.[^.]+$/, '.c') } ]) do |t| sh "cc #{t.source} -c -o #{t.name}" end rule '.class' => [ proc { |tn| tn.sub(/\.class$/, '.java').sub(/^classes\//, 'src/') } ] do |t| java_compile(t.source, t.name) end ``` -------------------------------- ### Rake Task Block Syntax Source: https://github.com/ruby/rake/blob/master/doc/rakefile.rdoc Illustrates the correct way to define task actions using do/end blocks in Rake. Using curly braces can lead to ambiguity with method calls. ```ruby # THIS IS FINE file "prog" => object_files do # Actions go here end ``` -------------------------------- ### Document Rake Tasks with `desc` Source: https://context7.com/ruby/rake/llms.txt Adds descriptions to Rake tasks, making them visible in the `rake -T` output. Tasks without `desc` are hidden from the task listing. This allows for better documentation and discoverability of build tasks. ```ruby # Rakefile desc "Run the full test suite" task :test do ruby "test/run_all.rb" end desc "Build the application for production" task build: [:clean, :compile, :optimize] do puts "Build complete!" end # Without desc, task won't appear in rake -T task :internal_task do # This task is hidden from listing end desc "Show all available tasks (even undocumented)" task :list do sh "rake -T -A" # -A shows all tasks end # View tasks: # rake -T # Show described tasks # rake -T build # Filter tasks matching 'build' # rake -D # Show full descriptions # rake -W # Show where tasks are defined ``` -------------------------------- ### Rake Task with Prerequisites and Parameters Source: https://github.com/ruby/rake/blob/master/doc/rakefile.rdoc Shows how to define a Rake task that has both named parameters and prerequisites. The prerequisites are specified using arrow notation before the task block. ```ruby task :name, [:first_name, :last_name] => [:pre_name] do |t, args| args.with_defaults(:first_name => "John", :last_name => "Dough") puts "First name is #{args.first_name}" puts "Last name is #{args.last_name}" end ``` -------------------------------- ### Rake Namespace Definition Source: https://github.com/ruby/rake/blob/master/doc/rakefile.rdoc Demonstrates how to define tasks within namespaces to prevent naming conflicts in larger projects. Tasks in different namespaces can have the same name. ```ruby namespace "main" do task :build do # Build the main program end end namespace "samples" do task :build do # Build the sample programs end end task build: %w[main:build samples:build] ``` -------------------------------- ### Rakefile Task Definitions and File Operations Source: https://context7.com/ruby/rake/llms.txt Defines Rake tasks for common file system operations such as creating directories, copying, moving, removing files, creating symbolic links, touching files, and changing permissions. It demonstrates the use of Rake's built-in file manipulation functions. ```ruby # Rakefile task :setup do # Create directories mkdir_p 'build/output' mkdir_p ['tmp', 'log', 'cache'] # Copy files cp 'config.example.yml', 'config.yml' cp_r 'templates', 'build/templates' # Move and rename mv 'old_name.rb', 'new_name.rb' # Remove files rm 'temp.txt' rm_f 'optional.txt' # Don't fail if missing rm_rf 'build' # Remove recursively # Create symbolic links (falls back to copy if not supported) safe_ln 'shared/config.yml', 'config.yml' # Touch files touch 'build/.timestamp' touch FileList['src/**/*.rb'] # Change permissions chmod 0755, 'bin/myapp' chmod 0644, FileList['lib/**/*.rb'] end ``` -------------------------------- ### Rake Execution Engine Source: https://github.com/ruby/rake/blob/master/doc/proto_rake.rdoc This function locates a Rakefile in the current or parent directories and executes the requested tasks. It handles command-line arguments and provides basic error reporting. ```ruby def rake begin here = Dir.pwd while ! File.exist?("Rakefile") Dir.chdir("..") fail "No Rakefile found" if Dir.pwd == here here = Dir.pwd end puts "(in #{Dir.pwd})" load "./Rakefile" ARGV.push("default") if ARGV.size == 0 ARGV.each { |task_name| Task[task_name].invoke } rescue Exception => ex puts "rake aborted ... #{ex.message}" puts ex.backtrace.find {|str| str =~ /Rakefile/ } || "" end end ``` -------------------------------- ### Import Dynamic Dependencies Source: https://github.com/ruby/rake/blob/master/doc/rakefile.rdoc Uses the import command to load generated dependency files after the Rakefile is loaded but before targets are invoked. ```ruby require 'rake/loaders/makefile' file ".depends.mf" => [SRC_LIST] do |t| sh "makedepend -f- -- #{CFLAGS} -- #{t.prerequisites} > #{t.name}" end import ".depends.mf" ``` -------------------------------- ### Define Rake Rules for Compilation Source: https://context7.com/ruby/rake/llms.txt Defines rules for Rake to automatically compile source files. It handles dependencies between file types like .o and .c, and supports complex transformations using regular expressions and proc blocks for flexible rule definition. It also shows how to specify multiple prerequisites for a task. ```ruby # Simple rule: .o files depend on .c files rule '.o' => '.c' do |t| sh "gcc -c -o #{t.name} #{t.source}" end # Rule with regular expression pattern rule(/\.o$/ => [ proc { |task_name| task_name.sub(/\.o$/, '.c') } ]) do |t| sh "gcc -c -o #{t.name} #{t.source}" end # Complex rule: .html from .md files in different directories rule '.html' => [ proc { |tn| tn.sub(/^output\//, 'src/').sub(/\.html$/, '.md') } ] do |t| mkdir_p File.dirname(t.name) sh "pandoc -o #{t.name} #{t.source}" end # Rule with multiple prerequisites rule '.o' => ['.c', '.h'] do |t| sh "gcc -c -o #{t.name} #{t.sources.first}" end # Now file tasks are auto-generated: # rake main.o # automatically finds main.c and compiles ``` -------------------------------- ### Define Directory Tasks Source: https://github.com/ruby/rake/blob/master/doc/rakefile.rdoc Illustrates the directory convenience method for creating directories on demand, which acts as a shorthand for recursive FileTasks. ```ruby directory "testdata/examples/doc" # Adding actions to directory tasks directory "testdata" file "testdata" do cp Dir["standard_data/*.data"], "testdata" end ``` -------------------------------- ### Invoke Rake tasks with arguments via command line Source: https://github.com/ruby/rake/blob/master/History.rdoc Shows the syntax for passing positional arguments to Rake tasks from the command line. Arguments are enclosed in brackets and separated by commas, requiring the task name and arguments to be treated as a single string. ```bash # Single argument rake release[0.8.2] # Multiple arguments rake name[john,doe] # Quoted arguments with spaces rake "name[billy bob, smith]" ``` -------------------------------- ### Utilize Enhanced File Utilities in Rake Source: https://context7.com/ruby/rake/llms.txt Rake enhances standard Ruby FileUtils methods to respect verbose and dry-run modes. This allows for safer and more controlled file operations within Rake tasks. ```ruby # Rakefile example demonstrating FileUtils usage # (Actual code snippet for FileUtils is not provided in the input text, # but this is where it would typically be used within a Rake task.) task :create_files do verbose(true) do mkdir_p 'output/subdir' touch 'output/file.txt' end end task :dry_run_example do dry_run = true # Simulate dry run Rake::FileUtilsExt.verbose = true Rake::FileUtilsExt.nowrite = dry_run mkdir_p 'temp_dir' touch 'temp_file.log' Rake::FileUtilsExt.nowrite = false # Reset for subsequent tasks end ``` -------------------------------- ### Execute Tasks in Parallel with Rake Source: https://github.com/ruby/rake/blob/master/History.rdoc Illustrates how to configure tasks to run in parallel using the 'multitask' feature in Rake. This is useful when multiple independent tasks can be executed concurrently to speed up the build process. ```ruby # Example of defining a multitask with parallelizable prerequisites # (Specific syntax for defining 'multitask' is not provided in the text, # but the concept is described.) # multitask :parallel_build => [:task1, :task2, :task3] ``` -------------------------------- ### Parallel Task Execution in Rake Source: https://github.com/ruby/rake/blob/master/History.rdoc Demonstrates how to define multiple tasks that will execute in parallel using Rake's multitasks feature. This is useful for speeding up build processes by running independent tasks concurrently. ```ruby multitask :copy_files => [:copy_src, :copy_doc, :copy_bin] do puts "All Copies Complete" end ``` -------------------------------- ### Rakefile Task for Controlling Verbosity and Dry-Run Source: https://context7.com/ruby/rake/llms.txt Demonstrates Rake's capabilities for controlling execution verbosity and enabling dry-run mode. The `verbose` block shows commands that will be echoed, while `nowrite` prevents actual file modifications during a dry run. ```ruby # Rakefile task :info do # Control verbosity verbose(true) do sh 'echo "This will be echoed"' end # Dry-run mode (no actual changes) nowrite(true) do rm_rf 'important' # Won't actually delete end end ``` -------------------------------- ### Execute shell commands with block callbacks in Rake Source: https://github.com/ruby/rake/blob/master/History.rdoc Demonstrates the use of the 'sh' command with a block to handle the result of a system call, allowing for custom logic based on the command's success status and exit code. ```ruby sh "shell_command" do |ok, res| puts "Program returned #{res.exitstatus}" if ! ok end ``` -------------------------------- ### Programmatically Manipulate Rake Tasks Source: https://github.com/ruby/rake/blob/master/doc/rakefile.rdoc Demonstrates how to clear prerequisites and actions of an existing Rake task using the Rake::Task lookup. ```ruby task :doit do puts "DONE" end task :dont do Rake::Task[:doit].clear end ``` -------------------------------- ### Check Code Style with RuboCop Source: https://github.com/ruby/rake/blob/master/CONTRIBUTING.rdoc This command uses RuboCop to enforce a consistent code style on new changes. It checks the code within the Rake project for style violations. ```bash #!/bin/bash cd /path/to/rake/project bin/rubocop ``` -------------------------------- ### Rake Package Task Options Source: https://github.com/ruby/rake/blob/master/History.rdoc Details the addition of 'tar_command' and 'zip_command' options to the Rake Package task. These options allow users to specify custom commands for tar and zip operations when creating packages. ```ruby # Example of setting tar_command and zip_command (syntax not provided) # package(:my_package) do |pkg| # pkg.tar_command = "gtar" # pkg.zip_command = "zip -9" # end ``` -------------------------------- ### Configuring Ruby Options for Rake TestTask Source: https://github.com/ruby/rake/blob/master/History.rdoc Demonstrates how to pass custom Ruby interpreter options to a test subprocess using the 'ruby_opts' attribute of Rake's TestTask. This allows for fine-grained control over the test execution environment. ```ruby Rake::TestTask.new do |t| t.libs << 'lib' t.ruby_opts << '-w' t.test_files = FileList['test/**/*_test.rb'] end ``` -------------------------------- ### Rakefile Task for Running Shell and Ruby Commands Source: https://context7.com/ruby/rake/llms.txt Defines a Rake task to execute external shell commands and Ruby scripts. It showcases running commands directly, passing arguments, executing Ruby code snippets, and handling command failures gracefully. ```ruby # Rakefile task :build do # Run shell commands sh 'npm install' sh 'npm', 'run', 'build' # Safer: no shell interpolation # Run ruby scripts ruby 'scripts/generate.rb' ruby '-e', 'puts RUBY_VERSION' # Handle command failures sh 'might_fail' do |ok, status| unless ok puts "Command failed with status #{status.exitstatus}" # Handle error or continue end end end ``` -------------------------------- ### Rake Task with Variable-Length Parameters Source: https://github.com/ruby/rake/blob/master/doc/rakefile.rdoc Illustrates a Rake task designed to accept a variable number of arguments using the `extras` method on the arguments object. This is useful for tasks that need to process a list of values. ```ruby task :email, [:message] do |t, args| mail = Mail.new(args.message) recipients = args.extras recipients.each do |target| mail.send_to(target) end end ``` -------------------------------- ### Finding TODO and FIXME Comments with Rake Source: https://github.com/ruby/rake/blob/master/History.rdoc Shows how to use Rake's FileList and egrep functionality to search for specific comments (TODO, FIXME, TBD) within Ruby files. This helps in identifying areas that need attention in the codebase. ```ruby desc "Look for TODO and FIXME tags in the code" task :todo do FileList['**/*.rb'].egrep /#.*(FIXME|TODO|TBD)/ end ``` -------------------------------- ### Rake Task with Default Parameter Values Source: https://github.com/ruby/rake/blob/master/doc/rakefile.rdoc Defines a Rake task with named parameters and provides default values for them using the `with_defaults` method. If arguments are not provided on the command line, these defaults will be used. ```ruby task :name, [:first_name, :last_name] do |t, args| args.with_defaults(:first_name => "John", :last_name => "Dough") puts "First name is #{args.first_name}" puts "Last name is #{args.last_name}" end ``` -------------------------------- ### Define Rake tasks with parameters Source: https://github.com/ruby/rake/blob/master/History.rdoc Demonstrates how to declare a Rake task that accepts named parameters and how to access those parameters within the task execution block. The task block receives the task object and an arguments object containing the passed values. ```ruby task :name, :first_name, :last_name do |t, args| puts "First name is #{args.first_name}" puts "Last name is #{args.last_name}" end ``` -------------------------------- ### Access Rake Task Programmatically Source: https://github.com/ruby/rake/blob/master/doc/rakefile.rdoc Demonstrates how to retrieve a Rake task object programmatically using `Rake::Task.[]`. This allows for manipulation or inspection of tasks within a Rakefile. ```ruby # Example of accessing a task named 'my_task' task_object = Rake::Task["my_task"] ``` -------------------------------- ### Define Automatic Cleanup Tasks with rake/clean Source: https://context7.com/ruby/rake/llms.txt Configures automatic cleanup tasks using the `rake/clean` library. It defines files to be removed by `rake clean` (temporary files) and `rake clobber` (all generated files, including those from `clean`). ```ruby # Rakefile require 'rake/clean' # CLEAN: temporary files removed by 'rake clean' CLEAN.include('**/*.o') CLEAN.include('**/*.log') CLEAN.include('tmp/**/*') CLEAN.include('*.tmp') # CLOBBER: generated files removed by 'rake clobber' (includes CLEAN) CLOBBER.include('build/**/*') CLOBBER.include('pkg/**/*') CLOBBER.include('doc/**/*') CLOBBER.include('coverage/**/*') # Build tasks that generate files directory 'build' file 'build/app' => ['build', 'src/main.c'] do |t| sh "gcc -o #{t.name} src/main.c" end task build: ['build/app'] # Usage: # rake clean # Remove temporary files (*.o, *.log, tmp/*) # rake clobber # Remove all generated files (runs clean first) ``` -------------------------------- ### File Path Manipulation with pathmap in Rake Source: https://github.com/ruby/rake/blob/master/History.rdoc Shows how to use the 'pathmap' method available for FileList and String objects in Rake. This method facilitates easier transformation of file paths, offering advanced globbing and path manipulation capabilities. ```ruby # Example usage of pathmap (specific syntax not provided in text) # file_list.pathmap(...) # string.pathmap(...) ``` -------------------------------- ### Filtering Tasks with Regular Expressions in Rake Source: https://github.com/ruby/rake/blob/master/History.rdoc Demonstrates how to filter the output of the '--task' option in Rake using a regular expression. This feature helps users quickly locate specific tasks within a large list of available tasks. ```bash # Example command to filter tasks (specific regex syntax not provided) # rake --tasks | grep 'your_regex' ``` -------------------------------- ### Rake's SafeLn Fallback Mechanism Source: https://github.com/ruby/rake/blob/master/History.rdoc Explains the bug fix in Rake version 0.7.1 where 'safe_ln' would fail with a NotImplementedError. Rake 0.7.1 now catches this error or any StandardError and falls back to using the 'cp' command. ```ruby # The following code illustrates the fallback mechanism, actual implementation may vary. begin # Attempt to use safe_ln safe_ln(source, destination) rescue NotImplementedError, StandardError => e # Fallback to using cp if safe_ln fails cp(source, destination) end ``` -------------------------------- ### Include Rake DSL Module in Ruby Source: https://github.com/ruby/rake/blob/master/History.rdoc To use Rake DSL commands within your own Ruby code, you need to include the Rake::DSL module. This makes methods like 'task', 'file', and 'directory' available in your custom classes or modules. This is necessary because these methods are no longer globally available in Object. ```ruby require 'rake' module MyTaskModule include Rake::DSL task :hello do puts "Hello from Rake DSL!" end end MyTaskModule.new.invoke(:hello) ``` -------------------------------- ### Rake CPU Count Detection via sysctl (Ruby) Source: https://github.com/ruby/rake/blob/master/History.rdoc For all BSD systems, Rake now uses the `sysctl` command to determine the number of CPUs. This ensures more accurate CPU counting on these platforms. Introduced in version 10.2.1. ```Ruby # This is an internal implementation detail of Rake's CPU detection. # Users do not need to write code for this, but it improves Rake's behavior on BSD systems. ``` -------------------------------- ### Rake CPU Count via sysctl for BSD (Ruby) Source: https://github.com/ruby/rake/blob/master/History.rdoc For all BSD-based systems, Rake utilizes the `sysctl` command to determine the number of CPUs, ensuring accurate detection. This was implemented in version 10.2.1. ```Ruby # Internal Rake logic for CPU detection on BSD systems. No direct user code required. ```