rake ruby что такое

RAKE – Ruby Make ¶ ↑

Description ¶ ↑

Rake is a Make-like program implemented in Ruby. Tasks and dependencies are specified in standard Ruby syntax.

Rake has the following features:

Rakefiles (rake’s version of Makefiles) are completely defined in standard Ruby syntax. No XML files to edit. No quirky Makefile syntax to worry about (is that a tab or a space?)

Users can specify tasks with prerequisites.

Rake supports rule patterns to synthesize implicit tasks.

Flexible FileLists that act like arrays but know about manipulating file names and paths.

A library of prepackaged tasks to make building rakefiles easier. For example, tasks for building tarballs. (Formerly tasks for building RDoc, Gems, and publishing to FTP were included in rake but they’re now available in RDoc, RubyGems, and rake-contrib respectively.)

Supports parallel execution of tasks.

Installation ¶ ↑

Gem Installation ¶ ↑

Download and install rake with the following.

Usage ¶ ↑

Simple Example ¶ ↑

First, you must write a “Rakefile” file which contains the build rules. Here’s a simple example:

This Rakefile has two tasks:

A task named “test”, which – upon invocation – will run a unit test file in Ruby.

A task named “default”. This task does nothing by itself, but it has exactly one dependency, namely the “test” task. Invoking the “default” task will cause Rake to invoke the “test” task as well.

Running the “rake” command without any options will cause it to run the “default” task in the Rakefile:

Type “rake –help” for all available options.

Resources ¶ ↑

Rake Information ¶ ↑

Presentations and Articles about Rake ¶ ↑

Avdi Grimm’s rake series:

Other Make Re-envisionings … ¶ ↑

Rake is a late entry in the make replacement field. Here are links to other projects with similar (and not so similar) goals.

directory.fsf.org/wiki/Bras – Bras, one of earliest implementations of “make in a scripting language”.

Credits ¶ ↑

Who originally created Rake.

Ryan Dlugosz

For the initial conversation that sparked Rake.

Nobuyoshi Nakada

For the initial patch for rule support.

Tilman Sauerbeck

For the recursive rule patch.

Eric Hodel

For aid in maintaining rake.

Hiroshi SHIBATA

Maintainer of Rake 10.X and Rake 11.X

License ¶ ↑

Rake is available under an MIT-style license.

Copyright © Jim Weirich

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Other stuff ¶ ↑

Copyright Jim Weirich. Released under an MIT-style license. See the MIT-LICENSE file included in the distribution.

Warranty ¶ ↑

This software is provided “as is” and without any express or implied warranties, including, without limitation, the implied warranties of merchantability and fitness for a particular purpose.

Historical ¶ ↑

Rake was originally created by Jim Weirich, who unfortunately passed away in February 2014. This repository was originally hosted at github.com/jimweirich/rake, however with his passing, has been moved to ruby/rake.

You can read more about Jim at Wikipedia.

Thank you for this great tool, Jim. We’ll remember you.

Источник

rake setup: Конфигурация окружения для работы проекта на Ruby On Rails

Доброго времени суток!

Перечитывая блог Signals Vs Noise я наткнулся на интересную статью

В ней рекомендовали создать rake задачу, которая полностью подготовит ваше приложение к разработке после клонирование из репозитория.

> All our apps has a rake setup task that’ll run bundler,
> create the databases, import seeds, and install any auxiliary
> software (little these days) or do any other setup. So when you git
> clone a new app, you know that “rake setup” will take care of you.

Я расскажу о том, как сделать подобную задачу в Ruby On Rails приложении.

Зайдем в папку с приложением и запустим
Данная команда выведет список всех задач, доступных для rake.

После того, как мы добавим нашу задачу, она тоже появится в этом списке.

Создаем новую Rake task

Он создаст скелет для нашей новой инструкции:
lib/tasks/setup.rake

Hello World

Пройдемся по лексемам только что созданной задачи

:hello_world — имя задачи.

=> :environment — зависимости. Перед тем как запустить основную задачу, Rake запускает все зависимые задачи. В данном случае запустится инструкция rake environment, которая включена в сборку RoR и позволяет работать с операциями, зависящими от окружения, например, использование базы данных.

Поприветствовать мир через rake будет просто. Добавим в тело задачи puts ‘Hello from rake!’ и запустим ее

Invoke

Это дает возможность создать ряд инструкций, которые с помощью встроенных Rails задач подготовят нашу базу к работе:

Мы удаляем старую базу, создаем новую, выполняем все миграции, добавляем начальные данные, и создаем базу для тестов. Это стандартные действия, которые делает каждый разработчик при установке приложения.

Работа с моделями

Внутри задачи мы можем работать с моделями точно так же, как в любом месте Rails приложения.

Собираем все вместе

Допишем в конце файла (вне блока namespace :setup) следующую инструкцию:

Запуск!

Все прошло как и было задумано! Поздравляю!

Заключение

После создания данной rake задачи на вас ложится еще одна ответственность — держать этот файл в актуальном состоянии, не забывайте про это.

И помните — вы не единственный разработчик. Если какая-то деталь кажется вам очевидной, то другой может потерять много времени до того как поймет как с ней работать. Старайтесь упростить разработку не только себе, но и коллегам.

Источник

Run Rake tasks

RubyMine provides a convenient way to run, debug, and reload Rake tasks. Moreover, you can use run/debug configurations to run tasks with specific parameters: you can pass task arguments, specify environment variables, and so on.

Before running a Rake task

Make sure the ‘rake’ gem is installed to the project SDK.

Check that the Rakefile is located in the project’s root.

Run a task

RubyMine allows you to run an arbitrary Rake task. For example, let’s see how to run the db:migrate task required for migrating a database in the Rails application:

Run a task using Run Anything

Do one of the following:

rake ruby что такое. Смотреть фото rake ruby что такое. Смотреть картинку rake ruby что такое. Картинка про rake ruby что такое. Фото rake ruby что такое

If you don’t see the desired Rake task in the dropdown, try reloading tasks.

rake ruby что такое. Смотреть фото rake ruby что такое. Смотреть картинку rake ruby что такое. Картинка про rake ruby что такое. Фото rake ruby что такое

Note that for other types of Rake tasks RubyMine provides the Arguments option for specifying the arguments to be passed to the task.

Run a task from the editor

In the *.rake file, do one of the following:

Click the Run Rake Task button on the gutter next to the required task.

Run a task using a run/debug configuration

You can also use the Services tool window to manage multiple run/debug configurations at once in a dedicated tool window.

Reload Rake tasks

Sometimes it is necessary to reload Rake tasks. For example, this can be useful if you created a custom task and need to run it. To reload Rake tasks, do one of the following:

Configure parameters for running a task

When you run a Rake task for the first time, RubyMine automatically creates a corresponding Rake temporary configuration, which can be saved. If necessary, you can create the Rake run/debug configuration manually from the predefined template.

To customize the run/debug configuration, do the following:

Open the Run/Debug Configuration dialog in one of the following ways:

Select Run | Edit Configurations from the main menu.

With the Navigation bar visible ( View | Appearance | Navigation Bar ), choose Edit Configurations from the run/debug configuration selector.

rake ruby что такое. Смотреть фото rake ruby что такое. Смотреть картинку rake ruby что такое. Картинка про rake ruby что такое. Фото rake ruby что такое

In the opened Run/Debug Configurations dialog, select the required configuration in the Rake group, and specify its settings.

rake ruby что такое. Смотреть фото rake ruby что такое. Смотреть картинку rake ruby что такое. Картинка про rake ruby что такое. Фото rake ruby что такое

Run/debug configuration: Rake

Configuration tab

In this field, specify the name of the current run/debug configuration.

Specify the name of the Rake task to be executed. Note that you can use autocompletion ( Ctrl+Space ) to see the available tasks.

If you don’t see the desired Rake task in the dropdown, try reloading tasks.

Specify arguments to be passed to the Rake task. These arguments should be separated with commas. For example:

Create the sample Rake task as shown below:

Create the Rake run configuration and specify its settings in the following way:

Arguments : «Andrew», «Fuller»

Run the created configuration. The program will return:

Attach test runner UI for frameworks

Depending on the used testing framework, enable the required test runner UI for performing tests.

Specify the working directory used by the running task. For example, this option is in effect when the running script loads other scripts by relative paths.

Specify the command-line arguments to be passed to the Ruby interpreter.

When such a run/debug configuration is launched, RubyMine analyzes the running processes, and does one of the following, depending on the presence of the running Nailgun server:

If there is no running Nailgun server, or if there is a Nailgun server on a non-default port, or with a different gemset, then RubyMine suggests to specify the desired port number.

If a Nailgun server runs on the default port with the required gemset, RubyMine does nothing.

If a Nailgun server runs on a different port with the required gemset, then RubyMine suggests to specify the desired port number.

Classpath property is added to Nailgun settings.

Specify the desired Ruby interpreter. You can choose the project default Ruby SDK, or select a different one from the list of configured Ruby SDKs.

Источник

Rake ruby что такое

First of all, there is no special format for a Rakefile. A Rakefile contains executable Ruby code. Anything legal in a ruby script is allowed in a Rakefile.

Now that we understand there is no special syntax in a Rakefile, there are some conventions that are used in a Rakefile that are a little unusual in a typical Ruby program. Since a Rakefile is tailored to specifying tasks and actions, the idioms used in a Rakefile are designed to support that.

So, what goes into a Rakefile?

Tasks are the main unit of work in a Rakefile. Tasks have a name (usually given as a symbol or a string), a list of prerequisites (more symbols or strings) and a list of actions (given as a block).

A task is declared by using the task method. task takes a single parameter that is the name of the task.

Tasks with Prerequisites ¶ ↑

Any prerequisites are given as a list (enclosed in square brackets) following the name and an arrow (=>).

NOTE: Although this syntax looks a little funky, it is legal Ruby. We are constructing a hash where the key is :name and the value for that key is the list of prerequisites. It is equivalent to the following …

You can also use strings for task names and prerequisites, rake doesn’t care. This is the same task definition:

We’ll prefer this style for regular tasks with prerequisites throughout the rest of the document. Using an array of strings for the prerequisites means you will need to make fewer changes if you need to move tasks into namespaces or perform other refactorings.

Tasks with Actions ¶ ↑

Actions are defined by passing a block to the task method. Any Ruby code can be placed in the block. The block may reference the task object via the block parameter.

A task may be specified more than once. Each specification adds its prerequisites and actions to the existing definition. This allows one part of a rakefile to specify the actions and a different rakefile (perhaps separately generated) to specify the dependencies.

For example, the following is equivalent to the single task specification given above.

Some tasks are designed to create a file from one or more other files. Tasks that generate these files may be skipped if the file already exists. File tasks are used to specify file creation tasks.

File tasks are declared using the file method (instead of the task method). In addition, file tasks are usually named with a string rather than a symbol.

It is common to need to create directories upon demand. The directory convenience method is a short-hand for creating a FileTask that creates the directory. For example, the following declaration …

The directory method does not accept prerequisites or actions, but both prerequisites and actions can be added later. For example …

Tasks with Parallel Prerequisites ¶ ↑

Rake allows parallel execution of prerequisites using the following syntax:

If any of the primary prerequisites of a multitask have common secondary prerequisites, all of the primary/parallel prerequisites will wait until the common prerequisites have been run.

For example, if the copy_xxx tasks have the following prerequisites:

The Rake internal data structures are thread-safe with respect to the multitask parallel execution, so there is no need for the user to do extra synchronization for Rake’s benefit. However, if there are user data structures shared between the parallel prerequisites, the user must do whatever is necessary to prevent race conditions.

Tasks with Arguments ¶ ↑

Prior to version 0.8.0, rake was only able to handle command line arguments of the form NAME=VALUE that were passed into Rake via the ENV hash. Many folks had asked for some kind of simple command line arguments, perhaps using “–” to separate regular task names from argument values on the command line. The problem is that there was no easy way to associate positional arguments on the command line with different tasks. Suppose both tasks :a and :b expect a command line argument: does the first value go with :a? What if :b is run first? Should it then get the first command line argument.

Rake 0.8.0 solves this problem by explicitly passing values directly to the tasks that need them. For example, if I had a release task that required a version number, I could say:

And the string “0.8.2” will be passed to the :release task. Multiple arguments can be passed by separating them with a comma, for example:

Just a few words of caution. The rake task name and its arguments need to be a single command line argument to rake. This generally means no spaces. If spaces are needed, then the entire name + argument string should be quoted. Something like this:

(Quoting rules vary between operating systems and shells, so make sure you consult the proper docs for your OS/shell).

Tasks that Expect Parameters ¶ ↑

Parameters are only given to tasks that are setup to expect them. In order to handle named parameters, the task declaration syntax for tasks has been extended slightly.

For example, a task that needs a first name and last name might be declared as:

The first argument is still the name of the task (:name in this case). The next two arguments are the names of the parameters expected by :name in an array (:first_name and :last_name in the example).

To access the values of the parameters, the block defining the task behaviour can now accept a second parameter:

The first argument of the block “t” is always bound to the current task object. The second argument “args” is an open-struct like object that allows access to the task arguments. Extra command line arguments to a task are ignored.

If you wish to specify default values for the arguments, you can use the with_defaults method in the task body. Here is the above example where we specify default values for the first and last names:

Tasks that Expect Parameters and Have Prerequisites ¶ ↑

Tasks that use parameters have a slightly different format for prerequisites. Use the arrow notation to indicate the prerequisites for tasks with arguments. For example:

Tasks that take Variable-length Parameters ¶ ↑

Tasks that need to handle a list of values as a parameter can use the extras method of the args variable. This allows for tasks that can loop over a variable number of values, and its compatible with named parameters as well:

There is also the convenience method to_a that returns all parameters in the sequential order they were given, including those associated with named parameters.

Deprecated Task Parameters Format ¶ ↑

There is an older format for declaring task parameters that omitted the task argument array and used the :needs keyword to introduce the dependencies. That format is still supported for compatibility, but is not recommended for use. The older format may be dropped in future versions of rake.

Accessing Task Programmatically ¶ ↑

Sometimes it is useful to manipulate tasks programmatically in a Rakefile. To find a task object use Rake::Task.[].

Programmatic Task Example ¶ ↑

For example, the following Rakefile defines two tasks. The :doit task simply prints a simple “DONE” message. The :dont class will lookup the doit class and remove (clear) all of its prerequisites and actions.

Running this example:

The ability to programmatically manipulate tasks gives rake very powerful meta-programming capabilities w.r.t. task execution, but should be used with caution.

When a file is named as a prerequisite, but does not have a file task defined for it, Rake will attempt to synthesize a task by looking at a list of rules supplied in the Rakefile.

Suppose we were trying to invoke task “mycode.o”, but no task is defined for it. But the rakefile has a rule that look like this …

This rule will synthesize any task that ends in “.o”. It has a prerequisite a source file with an extension of “.c” must exist. If Rake is able to find a file named “mycode.c”, it will automatically create a task that builds “mycode.o” from “mycode.c”.

If the file “mycode.c” does not exist, rake will attempt to recursively synthesize a rule for it.

When a task is synthesized from a rule, the source attribute of the task is set to the matching source file. This allows us to write rules with actions that reference the source file.

Any regular expression may be used as the rule pattern. Additionally, a proc may be used to calculate the name of the source file. This allows for complex patterns and sources.

The following rule is equivalent to the example above.

NOTE: Because of a quirk in Ruby syntax, parenthesis are required on rule when the first argument is a regular expression.

The following rule might be used for Java files …

NOTE: java_compile is a hypothetical method that invokes the java compiler.

Any ruby file (including other rakefiles) can be included with a standard Ruby require command. The rules and declarations in the required file are just added to the definitions already accumulated.

Because the files are loaded before the rake targets are evaluated, the loaded files must be “ready to go” when the rake command is invoked. This makes generated dependency files difficult to use. By the time rake gets around to updating the dependencies file, it is too late to load it.

The import command addresses this by specifying a file to be loaded after the main rakefile is loaded, but before any targets on the command line are invoked. In addition, if the file name matches an explicit task, that task is invoked before loading the file. This allows dependency files to be generated and used in a single rake command invocation.

If “.depends” does not exist, or is out of date w.r.t. the source files, a new “.depends” file is generated using makedepend before loading.

Standard Ruby comments (beginning with “#”) can be used anywhere it is legal in Ruby source code, including comments for tasks and rules. However, if you wish a task to be described using the “-T” switch, then you need to use the desc command to describe the task.

The “-T” switch (or “–tasks” if you like to spell things out) will display a list of tasks that have a description. If you use desc to describe your major tasks, you have a semi-automatic way of generating a summary of your Rake file.

Only tasks with descriptions will be displayed with the “-T” switch. Use “-P” (or “–prereqs”) to get a list of all tasks and their prerequisites.

As projects grow (and along with it, the number of tasks), it is common for task names to begin to clash. For example, if you might have a main program and a set of sample programs built by a single Rakefile. By placing the tasks related to the main program in one namespace, and the tasks for building the sample programs in a different namespace, the task names will not interfere with each other.

Referencing a task in a separate namespace can be achieved by prefixing the task name with the namespace and a colon (e.g. “main:build” refers to the :build task in the main namespace). Nested namespaces are supported.

Note that the name given in the task command is always the unadorned task name without any namespace prefixes. The task command always defines a task in the current namespace.

File task names are not scoped by the namespace command. Since the name of a file task is the name of an actual file in the file system, it makes little sense to include file task names in name space. Directory tasks (created by the directory command) are a type of file task and are also not affected by namespaces.

When looking up a task name, rake will start with the current namespace and attempt to find the name there. If it fails to find a name in the current namespace, it will search the parent namespaces until a match is found (or an error occurs if there is no match).

The “rake” namespace is a special implicit namespace that refers to the toplevel names.

If a task name begins with a “^” character, the name resolution will start in the parent namespace. Multiple “^” characters are allowed.

Here is an example file with multiple :run tasks and how various names resolve in different locations.

FileLists are the way Rake manages lists of files. You can treat a FileList as an array of strings for the most part, but FileLists support some additional operations.

Creating a FileList ¶ ↑

Creating a file list is easy. Just give it the list of file names:

Or give it a glob pattern:

Blocks may be specified with either a do / end pair, or with curly braces in Ruby. We strongly recommend using do / end to specify the actions for tasks and rules. Because the rakefile idiom tends to leave off parentheses on the task/file/rule methods, unusual ambiguities can arise when using curly braces.

For example, suppose that the method object_files returns a list of object files in a project. Now we use object_files as the prerequisites in a rule specified with actions in curly braces.

This is the proper way to specify the task …

When issuing the rake command in a terminal, Rake will look for a Rakefile in the current directory. If a Rakefile is not found, it will search parent directories until one is found.

For example, if a Rakefile resides in the project/ directory, moving deeper into the project’s directory tree will not have an adverse effect on rake tasks:

As far as rake is concerned, all tasks are run from the directory in which the Rakefile resides.

Multiple Rake Files ¶ ↑

Also, rails projects may include additional rake files in the lib/tasks directory.

Clean and Clobber Tasks ¶ ↑

Through require ‘rake/clean’ Rake provides clean and clobber tasks:

Clean up the project by deleting scratch files and backup files. Add files to the CLEAN FileList to have the clean target handle them.

You can add file names or glob patterns to both the CLEAN and CLOBBER lists.

The phony task can be used as a dependency to allow file-based tasks to use non-file-based-tasks as prerequisites without forcing them to rebuild. You can require ‘rake/phony’ to add the phony task.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *