From 7aa516d22924b54fcf5dc898a9826cc58908d37f Mon Sep 17 00:00:00 2001 From: Alexey Pyltsyn Date: Tue, 8 Jan 2019 22:09:00 +0300 Subject: [PATCH 01/10] README.md: translation --- README.md | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index d03cc45..e324aeb 100644 --- a/README.md +++ b/README.md @@ -1,13 +1,13 @@ -# Elixir and Elm Tutorial +# Руководство по Elixir и Elm -This repository contains the Markdown source files used to create the -[Elixir and Elm Tutorial](https://leanpub.com/elixir-elm-tutorial) book. +Репозиторий содержит Markdown-файлы, используемые для создания книги +[Руководство по Elixir и Elm](https://leanpub.com/elixir-elm-tutorial). -The latest changes are on the `preview` branch, and the published version -will be derived from the `master` branch. +Последние изменения находятся в ветке `preview`, +а окончательная версия — в ветке` master`. -## Need Help? +## Нужна помощь? -- Open a [GitHub Issue](https://github.com/elixir-elm-tutorial/elixir-elm-tutorial-book/issues). -- Email me at `bijanbwb@gmail.com`. +- Откройте [ишью на GitHub](https://github.com/elixir-elm-tutorial/elixir-elm-tutorial-book-ru/issues). +- Напишите электронное письмо на адрес `bijanbwb@gmail.com`. From 70150c808d4a9612474b640eb8a819d5b4a8c2e4 Mon Sep 17 00:00:00 2001 From: Alexey Pyltsyn Date: Tue, 8 Jan 2019 22:11:52 +0300 Subject: [PATCH 02/10] README.md: fixes --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e324aeb..7c3b63c 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ # Руководство по Elixir и Elm Репозиторий содержит Markdown-файлы, используемые для создания книги -[Руководство по Elixir и Elm](https://leanpub.com/elixir-elm-tutorial). +[Руководство по Elixir и Elm](https://leanpub.com/elixir-elm-tutorial-ru). Последние изменения находятся в ветке `preview`, а окончательная версия — в ветке` master`. From f119ddafc0d748ddfd0611c633cfa480129abddd Mon Sep 17 00:00:00 2001 From: Alexey Pyltsyn Date: Sun, 13 Jan 2019 17:14:10 +0300 Subject: [PATCH 03/10] introduction: translation --- manuscript/introduction.md | 243 +++++++++++++------------------------ 1 file changed, 83 insertions(+), 160 deletions(-) diff --git a/manuscript/introduction.md b/manuscript/introduction.md index f4c2885..c9c57b7 100644 --- a/manuscript/introduction.md +++ b/manuscript/introduction.md @@ -1,173 +1,96 @@ -# Introduction - -Welcome to the world of functional web programming! In this book, we'll **learn -how to create fun, scalable, and maintainable web applications**. We'll be -using a wide range of web technologies along with the latest ideas from -emerging languages like Elixir and Elm to craft a fun experience. Rather than -focusing on theory, we'll take a practical approach and build a real-world -application. - -## What We're Building - -**The application we'll be building together is a small game platform for the -web**. We'll use Elixir and the Phoenix web framework to power the back-end, -where players can sign in and keep track of their scores. Then, we'll use Elm -on the front-end to create fun minigames. We'll connect everything together so -we can pass data back and forth between the back-end and front-end. Users on -our platform will view available minigames, and the scores from those games -will be updated on the platform in real-time. We'll focus on building things -with a solid foundation so we can use these same concepts to create different -web applications as well. - -## Acknowledgements - -I would like to thank **Envy Labs** and **Code School** for fostering -environments where I was able to work hard and learn and grow. I'd also like -to thank **José Valim** and **Evan Czaplicki** for crafting such beautiful and -fun programming languages. And thanks to **Bret Victor** for inspiring all of -us with his visions of the future. - -## Who Is This Book For? - -This book is written for developers who already have _some_ existing experience -with web programming. The goal is for the book to be a practical introduction -to building a project with functional web programming languages like Elixir and -Elm. - -We won't assume any prior experience with Elixir and Elm, and consider it more -likely that you've worked with languages like Ruby and JavaScript. But **keep -in mind that we'll occasionally forego in-depth explanations and theory in an -effort to gain insight into shipping a real project**. - -We'll walk through initial explanations to give you just enough information -about the fundamentals and concepts so you can be productive. But there are -other books that will provide more depth when it comes to learning more about -the languages themselves: +# Введение + +Добро пожаловать в мир функционального веб-программирования! В этой книге мы узнаем, **как создавать увлекательные, масштабируемые и поддерживаемые веб-приложения**. Мы будем использовать широкий круг веб-технологий вместе с новейшими идеями развивающихся языков, таких как Elixir и Elm, чтобы получить уникальный опыт. Вместо того, чтобы сосредоточиться на теории, мы последуем практическому подходу и создадим реальное приложение. + +## Что будем разрабатывать + +**Приложение, которое мы будем создавать вместе, представляет собой небольшую игровую веб-платформу. Мы будем использовать Elixir и фреймворк Phoenix для поддержки бэкенда, где игроки могут входить в систему и отслеживать свои результаты. Затем мы воспользуемся Elm для фронтенда, чтобы создать забавные мини-игры. Мы объединим всё вместе для передачи данных туда и обратно между бэкендом и фронтендом. Пользователи нашей платформы будут просматривать доступные мини-игры, а результаты этих игр будут обновляться на платформе в режиме реального времени. Мы сосредоточимся на создании кода с прочной основой, так что мы могли использовать эти же концепции для создания различных веб-приложений. + +## Благодарности + +Я хотел бы поблагодарить **Envy Labs** и **Code School** за создание среды, в +которой я смог усердно работать, учиться и расти. Я также хотел бы поблагодарить +**Хосе Валима (José Valim)** и **Эвана Чаплицки (Evan Czaplicki)** за разработку +таких замечательных и интересных языков программирования. И спасибо **Брету +Виктору (Bret Victor)** за то, что он вдохновил всех нас своим представлением о +будущем. + +## Для кого эта книга? + +Эта книга написана для разработчиков, имеющих _некоторый_ опыт веб-разработки. Цель состоит в том, чтобы книга стала практическим введением в создание проекта с такими функциональными языками веб-программирования, как Elixir и Elm. + +Мы не предполагаем у вас какой-либо предыдущий опыт работы с Elixir и Elm и вместо этого считаем более вероятным, что вы работали с такими языками, как Ruby и JavaScript. Но **имейте в виду, что мы иногда пропускаем подробные объяснения и теорию для понимания, как реализовать настоящий проект**. + +Мы представим первоначальные объяснения и дадим достаточно информации про основы и концепции для продуктивной работы. Но есть и другие книги, в которых содержится более подробная информация, когда речь идет про изучение самих языков: - [Programming Elixir](https://pragprog.com/book/elixir16/programming-elixir-1-6) - by Dave Thomas -- [An Introduction to Elm](https://guide.elm-lang.org) by Evan Czaplicki + от Дэйва Томаса (Dave Thomas) +- [An Introduction to Elm](https://guide.elm-lang.org) от Эвана Чаплицки (Evan Czaplicki) -The material in this book is intended to be crafted in such a way that you can -follow along simply by typing in the relevant code examples. Beginners can -still learn a lot simply by following along and building the application, -because sometimes in programming you need to be exposed to certain concepts and -ideas before they become easy to understand. The experience of building -something will be fun and engaging; and a deeper understanding will follow with -increased familiarity and experience. +Материал в этой книге написан таким образом, чтобы вы могли следовать ему, просто набирая на клавиатуре соответствующие примеры кода. Новички все еще могут многому научиться, просто повторять за текстом и создавать приложение, потому что иногда в программировании вам необходимо ознакомиться с определенными концепциями и идеями, прежде чем они станут легкими для понимания. Опыт создания чего-либо будет веселым и увлекательным; и более глубокое понимание последует по мере увеличения знакомства и опыта. -## Prerequisites +## Обязательные условия -In addition to the notes above about the intended audience for this book, here -are some additional prerequisites to keep in mind: +В дополнение к приведенным выше примечаниям о целевой аудитории книги, далее приведены некоторые дополнительные предварительные условия, которые следует иметь в виду: -- Some experience with HTML and CSS. -- Familiarity with the command line and a text editor. -- Preferably previous experience with Git and GitHub. -- Preferably some experience working with a web framework. +- Определенный опыт работы с HTML и CSS. +- Знакомство с командной строкой и текстовым редактором. +- Желательно предыдущий опыт работы с Git и GitHub. +- Желательно некоторый опыт работы с каким-нибудь веб-фреймворком. -## Why Elixir and Elm? +## Почему Elixir и Elm? ### Elixir -[Elixir](http://elixir-lang.org) is a dynamic, functional language designed for -building scalable and maintainable applications. - -- Elixir is built on top of the Erlang virtual machine, and therefore inherits - _decades_ worth of stability and scalability. -- Concurrency is at the heart of Elixir. Instead of getting faster processors, - computers these days are getting processors with more cores. That means we - need to write our programs in such a way that allows them to be distributed - across multiple cores so our programs can outperform our competitors. As an - example, compare the latest - [13-inch Macbook Pro models](http://www.apple.com/shop/buy-mac/macbook-pro/13-inch) - with 2-core processors with - [15-inch Macbook Pro models](http://www.apple.com/shop/buy-mac/macbook-pro/15-inch) - with 6-core processors. Then, see how many cores (or "virtual CPUs") you'll - have access to when you deploy your application to a - [multi-core web server](https://www.digitalocean.com/pricing/#droplet). -- The Phoenix web framework provides us with the ability to create new projects - quickly. For web developers that have worked with Ruby on Rails, the concepts - will be familiar and easy to pick up. -- Elixir also inherits amazing features from other languages: - - - Ruby's readable syntax and philosophy of developer happiness. - - Erlang's stability and scalability. - - F#'s magical pipe operator for data transformation. - - LISP's macros and metaprogramming. +[Elixir](http://elixir-lang.org) — это динамический, функциональный язык, разработанный для создания масштабируемых и удобных в сопровождении приложений. + + +- Elixir построен на основе виртуальной машины Erlang и поэтому наследует _десятилетия_ стабильности и масштабируемости. +- Параллелизм занимает центральное место в Elixir. Вместо более быстрых процессоров компьютеры в наши дни имееют процессоры с большим количеством ядер. Это означает, что нам нужно писать программы таким образом, что их можно было распределить по нескольким ядрам, чтобы наши программы могли опередить конкурентов. В качестве примера, сравните последние [13-дюймовые модели Macbook Pro](http://www.apple.com/shop/buy-mac/macbook-pro/13-inch) с 2-ядерными процессорами и [15-дюймовые модели Macbook Pro](http://www.apple.com/shop/buy-mac/macbook-pro/15-inch) с 6-ядерными процессорами. Затем посмотрите, сколько ядер (или «виртуальных процессоров») вы получите при развертывании приложения на [многоядерном веб-сервере](https://www.digitalocean.com/pricing/#droplet). +- Фреймворк Phoenix дает нам возможность быстро создавать новые проекты. Для веб-разработчиков, ранее работавших с Ruby on Rails, концепции будут знакомы и просты в освоении. +- Elixir также наследует удивительные особенности от других языков: + - Читаемый синтаксис от Ruby и философия счастья у разработчика. + - Стабильность и масштабируемость из Erlang. + - Магический оператор конвейера с языка F# для преобразования данных. + - Макросы и метапрограммирование от LISP. ### Elm -[Elm](http://elm-lang.org) is an exciting new functional language that is still -evolving. It's the fastest, most reliable front-end web programming language -currently available. - -- Elm is a compiled, functional language. -- Elm is _blazingly_ fast. -- Elm programs are free from runtime errors. That means the language was - designed in such a way that makes a certain class of errors impossible, which - provides us with an ability to make guarantees about how our programs work. -- The Elm compiler can be a helpful guide towards writing high quality code, - and the error messages provided are extremely helpful. -- The elm-format tool helps with writing consistent code that is easier to - read, write, and maintain. While optional, this tool is _highly_ recommended - for Elm beginners because you can configure it to automatically format code - when you save a file in your editor. -- With all the features Elm has to offer, the net result is confidence. As - developers, we can be more confident that our code is performing the way - we intended, and that our programs will function properly for our users. -- Elm code is maintainable. Refactoring is a dream, and you'll find yourself - surprised at how easy a significant refactor can feel after coming from other - languages. - -### Elixir and Elm? - -**Elixir and Elm are young, functional programming languages that are optimized -for your happiness as a developer. They offer a programming experience that -will make it fun to develop applications, and over time those applications will -be easy to extend and maintain**. - -The primary reason to pick up new languages like Elixir and Elm is that it will -afford you with an opportunity to acquire new ways of thinking. Many great -lessons have been learned in the field of programming over the past several -decades, and unfortunately many developers are still working in the dark on a -daily basis. We ignore history at a great cost, and all too often make things -difficult on ourselves. Elixir and Elm are a chance at a fresh perspective. - -## Technology Stack - -There are _many_ technologies involved in building and deploying modern web -applications. We'll be using a straightforward stack of technologies that will -allow us the flexibility to scale our applications gracefully. Here's the short -version of the technology stack: - -- Back-end: Elixir -- Front-end: Elm - -These technologies stand on the shoulders of giants, so here's a little more -information about other technologies we'll also use while building our -applications: - -- Back-end: Elixir and Phoenix -- Front-end: Elm, the Elm Architecture, and JavaScript -- Version Control: Git and GitHub -- Data: Ecto, PostgreSQL, and JSON -- Deployment: Heroku - -## Functional Programming - -If you're coming from a background in working with Ruby on Rails or JavaScript -web frameworks, then you'll have a head start in being able to grasp the -content and move smoothly through the book. Something to keep in mind is that -Elixir and Elm are _functional_ languages. If you're coming from an -_object-oriented_ background, you may find some of the concepts unfamiliar at -first, but the initial discomfort will pay off over time as you learn to solve -problems in an elegant functional manner. - -## Summary - -In this introduction, we touched briefly on the application we'll be building -and some of the reasoning for choosing Elixir and Elm as languages. But the -fun part is _creating_ with these technologies and _experiencing_ the benefits -first-hand, so let's dive in and start building our application in the next -chapter. +[Elm](http://elm-lang.org) — это новый захватывающий функциональный язык, который продолжает разрабатываться. Это самый быстрый, самый надежный язык веб-программирования для фронтенда, доступный в настоящее время. + +- Elm — это компилируемый и функциональный язык. +- Elm _удивительно_ быстрый. +- Программы на Elm не подвержены ошибками во время выполнения. Это означает, что язык разработан таким образом, что делает определенный класс ошибок невозможным, что в свою очередь дает нам возможность гарантировать относительно того, как работают наши программы. +- Компилятор Elm может послужить полезным руководством для написания высококачественного кода, а приведенные сообщения об ошибках _чрезвычайно_ полезны. +- Инструмент elm-format помогает в создании единообразного кода, который легче читать, писать и поддерживать. Хотя этот инструмент необязательный для использования, он настоятельно рекомендуется новичкам в Elm, поскольку можно настроить его, чтобы он автоматически форматировал код при сохранении файла в редакторе. +- Благодаря всем возможностям, предлагаемые Elm, конечным результатом является уверенность. Как разработчики, мы можем быть более уверены в том, что наш код работает так, как мы задумали, а наши программы будут работать должным образом для пользователей. +- Код Elm — легкий для сопровождения. Рефакторинг — это мечта, и вы удивитесь тому, как легко его делать после перехода с других языков. + +### Elixir и Elm? + +**Elixir и Elm — это новые, функциональные языки программирования, которые оптимизированы для вашего счастья как разработчика. Они предлагают опыт программирования, который сделает разработку приложений увлекательной, и со временем эти приложения будут легкими для расширения и поддержки**. + +Основная причина выбора новых языков, таких как Elixir и Elm, заключается в том, что они дадут возможность приобрести новые способы мышления. За последние несколько десятилетий было извлечено много замечательных уроков в области программирования, и, к сожалению, многие разработчики все еще ежедневно работают вслепую. Игнорирование истории обходится нам большими затратами и мы слишком часто усложняем себе жизнь. Elixir и Elm — это шанс на новый взгляд. + +## Технологический стек + +Существует _много_ технологий, которые используется для создания и развертывания современных веб-приложений. Мы будем использовать простой стек технологий, позволяющий гибко масштабировать наши приложения. Вот сокращенный вариант стека технологий: + +- Бэкенд: Elixir +- Фронтенд: Elm + +Эти технологии опираются на плечи гигантов, поэтому вот еще немного данных про другие технологии, которые мы также будем использовать: + +- Бэкенд: Elixir и Phoenix +- Фронтенд: Elm, архитектура Elm и JavaScript +- Система контроля версий: Git и GitHub +- Данные: Ecto, PostgreSQL и JSON +- Развертывание: Heroku + +## Функциональное программирование + +Если вы ранее работали с Ruby on Rails или JavaScript-фреймворками, то у вас есть преимущество в понимании и плавном изучении книги. Нужно только помнить, что Elixir и Elm являются _функциональными_ языками. Если у вас опыт с _объектно-ориентированным подходом_, вы можете сначала найти определенные понятия незнакомыми, однако некоторый дискомфорт со временем окупится, когда вы научитесь решать проблемы весьма элегантным функциональным способом. + +## Резюме + +В этом введении мы кратко затронули создаваемое приложение, а также некоторые причины выбора Elixir и Elm в качестве используемых языков. Но самое интересное — это _создание_ с использованием этих технологий и непосредственное _использование преимуществ_, поэтому давайте углубимся и начнем создавать наше приложение в следующей главе. From 8e7ea750d9abbf7ef6a8ee6d85cfe0ae4bcc9f4c Mon Sep 17 00:00:00 2001 From: Alexey Pyltsyn Date: Mon, 14 Jan 2019 01:26:58 +0300 Subject: [PATCH 04/10] diving_in: initial translation --- manuscript/diving_in.md | 291 ++++++++++++---------------------------- 1 file changed, 84 insertions(+), 207 deletions(-) diff --git a/manuscript/diving_in.md b/manuscript/diving_in.md index fb07bc9..eabe332 100644 --- a/manuscript/diving_in.md +++ b/manuscript/diving_in.md @@ -1,40 +1,28 @@ -# Diving In +# Приступаем к работе -Instead of simply _reading_ about Elixir and Elm, let's dive in and -_experience_ what these languages have to offer. In this chapter, we're going -to avoid detailed explanations and theory in favor of quickly building the -foundation for our project. We'll focus on running the necessary commands in -the Terminal and writing the code we'll need to start creating our application. +Вместо того, чтобы просто _читать_ про Elixir и Elm, давайте погрузимся и _познакомимся_ с тем, что могут предложить эти языки. В данной главе мы пропустим подробные объяснения и теорию в пользу быстрого создания заготовки для нашего проекта. Мы сосредоточимся на запуске необходимых команд в терминале и написании кода, который нам понадобится для начала разработки приложения. -Later in the book, we'll cover more about the fundamentals of Elixir, but for -now let's focus on following along and getting a glimpse of how to get an -application up and running. +Позже в книге мы расскажем больше об основах Elixir, но сейчас давайте обратим внимание на то, чтобы следовать инструкциям, указанным в книге, а также бегло ознакомимся с тем, как настроить и запустить приложение. -## Installation +## Установка -If you haven't already set up your development environment with Elixir, -Phoenix, and PostgreSQL, **check out the [Appendix](#appendix) in the back -of the book for quick installation instructions**. +Если вы еще не настроили собственную среду для разработки на Elixir, Phoenix и PostgreSQL, **ознакомьтесь с [Приложением](#appendix) в конце книги для получения соответствующих инструкций по быстрой установке**. -Also note that we're working with the _latest_ version of Phoenix in this book. -Make sure you have **Phoenix 1.4** installed, or the commands and files will -all look different as you work through the material. +Также обратите внимание, что мы работаем с _последней_ версией Phoenix в этой книге. Убедитесь, что у вас установлен **Phoenix 1.4**, иначе команды и файлы будут выглядеть по-разному во время работы с материалом. -## Creating the Platform +## Создание платформы -The first step we need to take is to create the foundation for our application. -To do that, let's open up our Terminal and run the following command: +Первый шаг, который нам нужно сделать, — создать заготовку для нашего приложения. Для этого откроем терминал и запустим следующую команду: ```shell $ mix phx.new platform ``` -It will ask the following question: +Команда задаст следующий вопрос: > Fetch and install dependencies? -Enter the letter `Y` and the following output will be displayed (note that some -of the file creation lines were trimmed for the sake of readability): +Введите букву `Y` и отобразится следующий вывод (обратите внимание, что некоторые строчки создания файлов были обрезаны для удобства чтения): ```shell $ mix phx.new platform @@ -51,58 +39,45 @@ Fetch and install dependencies? [Yn] Y * running mix deps.get * running mix deps.compile * running cd assets && npm install && node node_modules/webpack/bin/webpack.js --mode development +``` -We are all set! Go into your application by running: +У нас все готово! Зайдите в приложение путем его запуска: $ cd platform -Then configure your database in config/dev.exs and run: +Затем настройте базу данных в файле `config/dev.exs` и выполните команду ниже: $ mix ecto.create -Start your Phoenix app with: +Запустите приложение на Phoenix следующим образом: $ mix phx.server -You can also run your app inside IEx (Interactive Elixir) as: +Вы также можете запустить приложение внутри IEx (Interactive Elixir) вот так: $ iex -S mix phx.server -``` -Phoenix displays _a lot_ of helpful information. First, the output shows all -the files that were generated (don't worry if it seems overwhelming at first; -we're only going to start with a handful of these files). Then, we see some -information about how to configure our database and start the server. +Phoenix отображает _много_ полезной информации. Во-первых, в выводе отображаются все сгенерированные файлы (не беспокойтесь, если на первый взгляд вывод кажется огромным; мы начнем только с нескольких этих файлов). Затем мы видим некоторую информацию о том, как настроить базу данных и запустить сервер. -## Configuring the Database +## Настройка базы данных -Now that we've created the files for our Phoenix application, let's change to -that directory: +Теперь как мы создали файлы для нашего приложения Phoenix, давайте перейдем к нужной директории: ```shell $ cd platform ``` -We can set up the database for our project by running the following command: +Мы можем настроить базу данных для проекта, если выполним следующую команду: ```shell $ mix ecto.create ``` -If you run into issues here, it likely means you'll have to configure your -PostgreSQL installation or adjust the database `username` and `password` fields -at the bottom of the `config/dev.exs` file. You can also check out the -[Appendix](#appendix) at the back of this book for more information on -PostgreSQL. +Если вы столкнетесь с проблемами при выполнении команд — это, вероятно, значит, что предстоит установить PostgreSQL или настроить поля `username` и `password` в нижней части файла `config/dev.exs`. Вы также можете заглянуть в [Приложение](#appendix) в конце книги для получения дополнительной информации о PostgreSQL. -Since this is the first time we're running a command with our new application, -we'll see that it takes time for the source code to compile. Elixir runs on the -Erlang virtual machine, and needs to compile the source to bytecode before we -can run our programs. It takes time to run initially, but subsequent commands -will run noticeably faster after this. +Поскольку мы впервые запускаем команду с нашим новым приложением, мы увидим, что для компиляции исходного кода потребуется некоторое время. Elixir работает на виртуальной машине Erlang и должен скомпилировать исходный код в байт-код, прежде чем мы сможем запустить наши программы. На первоначальном этапе нужно время для запуска, но последующие команды будут работать заметно быстрее. -If the database creation was successful, we'll see the following message at the -bottom: +Если создание базы данных прошло успешно, мы увидим следующее сообщение внизу: ```shell $ mix ecto.create @@ -111,42 +86,28 @@ Generated platform app The database for Platform.Repo has been created ``` -We have successfully created our Phoenix application, compiled it, and set up -our database. +Мы успешно создали приложение Phoenix, скомпилировали его и настроили базу данных. -## Running the Server +## Запуск сервера -Let's see what our new application looks like in the browser. To start the web -server, run the following command: +Посмотрим, как выглядит приложение в браузере. Чтобы запустить веб-сервер, выполните следующую команду: ```shell $ mix phx.server ``` -This will start a server and allow us to visit -[`http://localhost:4000`](http://localhost:4000) in a browser to see our new -application running. Here is what the output will look like (ignoring the -additional output from Webpack): +Команда выше запустит сервер, доступный по URL-адресу [`http://localhost:4000`](http://localhost:4000) из браузера, чтобы увидеть, как работает наше новое приложение. Вот как будет выглядеть вывод (игнорируя дополнительный вывод от Webpack): ```shell $ mix phx.server [info] Running PlatformWeb.Endpoint with cowboy using http://localhost:4000 ``` -![Phoenix Default Start Page](images/diving_in/phoenix_start.png) +![Начальная страница Phoenix по умолчанию](images/diving_in/phoenix_start.png) -At this point, you might be impressed that we managed to get a full back-end -up and running so quickly. Or, you may have seen similar features in other -frameworks, and perhaps you're nonplussed with our progress so far. We're going -to start adding features to our application, but it's worth taking a moment to -appreciate how much we already have going for us with just a few commands. +На данном этапе вас может впечатлить то, что нам удалось создать и запустить так быстро полноценный бэкенд. Хотя, возможно, вы наблюдали подобные возможности у других фреймворках, и поэтому вы пока нисколько не удивлены текущими результатами. Мы собираемся начать разработку функционала приложения, но стоит задуматься на мгновение и оценить, сколько же у нас всякого, созданного всего лишь с помощью нескольких команд. -Feel free to take a look at some of the great documentation listed on the -default Phoenix start page. Before we move on, let's stop the Phoenix web -server. Go back to the Terminal where the server is running, and press -`Control + C` on your keyboard _twice_ to stop the server. This tends to be the -simplest way to exit a running Elixir program, and here is what the output will -look like as you stop the running web server: +Не стесняйтесь посмотреть на определенные разделы замечательной документации, которые перечислены на начальной странице Phoenix по умолчанию. Прежде чем мы продолжим, давайте остановим веб-сервер Phoenix. Вернитесь в окно терминала, где запущен сервер, и _дважды_ нажмите `Control + C` на клавиатуре для остановки сервера. Это, как правило, самый простой способ выйти из выполняющейся программы на Elixir, и вот как будет выглядеть вывод при завершении работы сервера: ```shell $ mix phx.server @@ -164,41 +125,28 @@ BREAK: (a)bort (c)ontinue (p)roc info (i)nfo (l)oaded $ ``` -## Our First Resource +## Первый ресурс -Since we are building a small game platform, there are two primary resources -that we'll want to get started with: +Поскольку мы создаем небольшую игровую платформу, есть два основных ресурса, с которых нам лучше начать: -- Players -- Games +- Игроки +- Игры -We're going to start by using something called a generator to keep moving -quickly. It's going to create a lot of the files we need to work with. Then, -we'll cover more about how it all works later. +Мы собираемся начать с использования так называемого генератора, чтобы быстрее двигаться. Он создаст много файлов, с которыми нужно работать. Затем позже мы узнаем больше про то, как все это работает. -Let's generate the resource for our players with the following command: +Давайте сгенерируем ресурс для наших игроков с помощью следующей команды: ```shell $ mix phx.gen.html Accounts Player players username:string score:integer ``` -With this command, we're creating players for our game platform. We want to be -able to use our browser to interact with the data, so we're starting with -[`phx.gen.html`](https://hexdocs.pm/phoenix/Mix.Tasks.Phx.Gen.Html.html) to -generate an HTML resource. +С помощью этой команды мы создаем игроков для нашей игровой платформы. Мы хотим использовать браузер для работы с данными, поэтому мы начинаем с файла [`phx.gen.html`](https://hexdocs.pm/phoenix/Mix.Tasks.Phx.Gen.Html.html), чтобы создать HTML-ресурс. -Because we're creating player accounts for our application, we use `Accounts` -to provide a _context_ for our resource. Then, we use `Player` for the module -name and `players` to indicate the pluralized form, which will also be used -to create the database table. +Поскольку мы создаем учетные записи игроков для разрабатываемого приложения, мы используем `Accounts`, чтобы предоставить _контекст_ для нашего ресурса. Затем мы используем `Player` в качестве имени модуля и `players`, чтобы указать на множественную форму, которая также будет использоваться для создания таблицы базы данных. -For the player fields, each player account will have a `username` (stored as a -string), and a `score` (stored as an integer). We'll eventually extend the -capabilities of our players with additional fields, but for now this will -give us a good starting point to start creating a list of players. +Для полей игрока каждый аккаунт игрока будет иметь имя пользователя (`username`, хранится в виде строки) и счет (`score`, хранится как целое число). Со временем мы расширим потенциал наших игроков дополнительными полями, но пока это даст нам хорошую отправную точку для начала создания списка игроков. -You'll see that the generator creates quite a few files for us, and once again -Phoenix gives us some helpful tips about what to do next: +Вы увидите, что генератор создает довольно много файлов, и в очередной раз Phoenix дает нам несколько полезных советов по поводу дальнейших действий: ```shell $ mix phx.gen.html Accounts Player players username:string score:integer @@ -216,26 +164,21 @@ $ mix phx.gen.html Accounts Player players username:string score:integer * injecting lib/platform/accounts/accounts.ex * creating test/platform/accounts/accounts_test.exs * injecting test/platform/accounts/accounts_test.exs +``` -Add the resource to your browser scope in lib/platform_web/router.ex: +Добавьте ресурс в область видимости браузера в файл `lib/platform_web/router.ex`: resources "/players", PlayerController -Remember to update your repository by running migrations: +Не забудьте обновить репозиторий, запустив миграцию: $ mix ecto.migrate -``` -## Routing +## Маршрутизация -Don't worry too much about all those files yet, but the information at the -bottom is important. In order to configure our application to work with our new -player accounts, we'll need to add them to the router first, and then run a -migration to update the database with a new `players` table. +Пока не беспокойтесь о всех этих файлах, но информация ниже важна. Чтобы настроить приложение для работы с нашими новыми учетными записями игроков, нужно сначала добавить их в маршрутизатор, а затем запустить миграцию для обновления базы данных (добавить новую таблицу `players`). -Phoenix makes things easy on us with the helpful notes in the Terminal. Let's -go ahead and follow along. Open the `lib/platform_web/router.ex` file and see -what it looks like: +Phoenix облегчает нам задачу с помощью полезных заметок в терминале. Давайте пойдем вперед и повторяем, что написано далее. Откройте файл `lib/platform_web/router.ex` и посмотрите, как он выглядит: ```elixir defmodule PlatformWeb.Router do @@ -266,13 +209,7 @@ defmodule PlatformWeb.Router do end ``` -The Phoenix router comes with two separate "pipelines" by default. One of them -is for HTML (which we're going to use now), and the other one is for JSON -(which we'll also use later). And we can even see that the `scope` is already -set up for us to access the HTML with our browser. That's how we were able to -load the `http://localhost:4000` URL and see the initial starter page. Don't -worry if it seems confusing at first. All you need to know is that this block -of code is where we'll focus for now: +Маршрутизатор Phoenix поставляется с двумя отдельными «конвейерами» по умолчанию. Один из них предназначен для HTML (который мы собираемся использовать в данный момент), а другой — для JSON (который мы также будем использовать, но позже). И мы даже можем видеть, что `scope` уже настроена для доступа к HTML через браузер. Вот так мы смогли открыть URL-адрес `http://localhost:4000` и увидеть начальную стартовую страницу. Не волнуйтесь, если это поначалу кажется непонятным. Учтите только одно — сейчас мы остановимся на этом блоке кода: ```elixir scope "/", PlatformWeb do @@ -282,7 +219,7 @@ scope "/", PlatformWeb do end ``` -And we're going to update it with our new players resource: +Далее мы собираемся обновить этот фрагмент, добавив новый ресурс игроков: ```elixir scope "/", PlatformWeb do @@ -293,24 +230,17 @@ scope "/", PlatformWeb do end ``` -That means when we access -[`http://localhost:4000/players`](http://localhost:4000/players), we'll -soon be able to start creating the players for our game platform. +Это означает, что когда мы получим доступ к [`http://localhost:4000/players`](http://localhost:4000/players), мы скоро сможем начать создавать игроков для нашей игровой платформы. -## Running a Migration +## Запуск миграции -Our application has all the information it needs to render the players resource -that we created, but we still need to tell the database about the changes we -made. For the database to store our player data (with the `username` and -`score` fields), we'll need to run a migration. Go back to the Terminal, and -run the following command: +Наше приложение содержит всю информацию, необходимую для отображения созданного нами ресурса игроков, но нам все еще нужно сообщить базе данных про внесенные изменения. Чтобы база данных сохраняла данные наших игроков (с полями `username` и `score`), нужно выполнить миграцию. Вернитесь в терминал и выполните следующую команду: ```shell $ mix ecto.migrate ``` -This will create a new database table called `players`. If everything -goes according to plan, then we should see the following output: +Это создаст новую таблицу базы данных `players`. Если все идет по плану, то мы должны увидеть следующий вывод: ```shell $ mix ecto.migrate @@ -321,56 +251,39 @@ Generated platform app 08:18:44.371 [info] == Migrated in 0.1s ``` -## Creating Players +## Создание игроков -Let's start our server again and see our new player resource in action: +Давайте снова запустим сервер и увидим ресурс игрока в действии: ```shell $ mix phx.server ``` -Now we can access -[http://localhost:4000/players](http://localhost:4000/players) and we should -see the following: +Теперь мы можем перейти по адресу +[http://localhost:4000/players](http://localhost:4000/players) и увидим +следующее: -![Empty List of Players on Player Index Page](images/diving_in/empty_players_list.png) +![Пустой список игроков на индексной странице игрока](images/diving_in/empty_players_list.png) -This is excellent. We can now add players to our platform using a web browser. -Click the **New Player** link at the bottom and try creating a player on the -[`http://localhost:4000/players/new`](http://localhost:4000/players/new) page. +Прекрасно, теперь мы можем через браузер добавлять игроков на платформу. Нажмите на ссылку **New Player** внизу и попробуйте создать игрока на странице [`http://localhost:4000/players/new`](http://localhost:4000/players/new). -![New Player Page](images/diving_in/new_player.png) +![Страница нового игрока](images/diving_in/new_player.png) -After we successfully create a new player account, we'll see the "show" page -with the individual player's data (notice the player `id` number is displayed -in the URL too): +После того, как мы успешно создадим новую учетную запись игрока, мы перейдем на страницу с псевдонимом «show», на которой будут отображены данные по конкретному игроку (обратите внимание, что идентификатор (`id`) игрока также отображается в URL-адресе): -![Player Show Page](images/diving_in/new_player_created.png) +![Страница отображения информации об игроке](images/diving_in/new_player_created.png) -Feel free to create additional player accounts so we have data to work with on -our players page: +Не стесняйтесь создавать дополнительные учетные записи игроков, поскольку эти данные выводятся на странице игроков: -![Players Index with Sample Data](images/diving_in/list_players.png) +![Страница со списком игроков с демонстрационными данными](images/diving_in/list_players.png) -## Updating our Home Page +## Обновление главной страницы -We have a working players resource with an index of all the players, a show -page to view a single player, an edit page to update a single player, and the -ability to delete players. But when we go back to our home page at -[`http://localhost:4000`](http://localhost:4000), these pages aren't accessible. -Our users wouldn't know that they need to visit the `/players/new` page to -create their account. At some point, we will only want our users to be able to -create their accounts without being able to edit or delete others. To get -started, let's figure out where the HTML code is coming from for our home page. +У нас есть работающий ресурс игроков с индексной страницей всех игроков, страница отображения игрока, страница редактирования для обновления данных по игроку, а ещё возможность удаления игроков. Но когда мы возвращаемся на нашу домашнюю страницу по адресу [`http://localhost:4000`](http://localhost:4000), эти страницы не доступны. Наши пользователи не знают, что им нужно посетить страницу `/players/new` для создания своего аккаунта. Рано или поздно мы захотим, чтобы наши пользователи могли создавать свои учетные записи, при этом не редактируя и не удаляя другие. Для начала давайте выясним, откуда приходит HTML-код для нашей домашней страницы. -Inside the `lib/platform_web` folder, there is a `templates` folder. This is -where we put the HTML code that we want to render in the browser. And instead -of standard `.html` files, we'll see that the files have a `.html.eex` -extension. That means we can write standard HTML code, and we can also embed -Elixir code too. +Внутри директории `lib/platform_web` есть директория `templates`. Здесь мы храним HTML-код, который показывается в браузере. И вместо обычных файлов с расширением `.html` мы увидим, что файлы имеют расширение `.html.eex`. Это означает, что мы можем писать знакомый нам HTML-код, а также встроить код на Elixir. -Let's open the `lib/platform_web/templates/page/index.html.eex` file and take a -look (note that some of the HTML was trimmed for the sake of readability): +Давайте откроем файл `lib/platform_web/templates/page/index.html.eex` и посмотрим его содержимое (обратите внимание, что часть кода HTML была обрезана для удобства чтения): ```embedded_elixir
@@ -390,12 +303,7 @@ look (note that some of the HTML was trimmed for the sake of readability):
``` -This should look familiar in that it's mostly comprised of standard HTML code. -It's the HTML that we're seeing when we load -[`http://localhost:4000`](http://localhost:4000). Let's delete this code and create -a couple of simple links to our player pages. First, remove _all_ the existing -code in the `lib/platform_web/templates/page/index.html.eex` file. Then, -replace it with the following: +Это должно выглядеть знакомо, поскольку в основном код состоит из обычного HTML-кода. Это HTML-код, который мы видим при загрузке [`http://localhost:4000`](http://localhost:4000). Давайте удалим этот код и создадим пару простых ссылок на страницы игроков. Сначала удалите _весь_ существующий код в файле `lib/platform_web/templates/page/index.html.eex`. Затем замените его на следующий: ```html
@@ -404,37 +312,21 @@ replace it with the following:
``` -Save the file and go back to the browser to see the changes (make sure the -Phoenix web server is still running or restart the server with -`mix phx.server`) at [`http://localhost:4000`](http://localhost:4000): +Сохраните файл и вернитесь в браузер, чтобы увидеть изменения (убедитесь, что веб-сервер Phoenix все еще запущен, либо перезапустите сервер с помощью `mix phx.server`) по адресу [`http://localhost:4000`](http://localhost:4000): -![Home Page with List Players Link](images/diving_in/updated_home_page.png) +![Главная страница со ссылкой на списком игроком](images/diving_in/updated_home_page.png) -Phoenix comes with a **Live Reload** feature that automatically refreshes our -application in the browser. If the Phoenix server was still running, then the -home page was automatically regenerated and should now display the buttons that -we created. Try them out, and they should enable users to successfully navigate -to the player pages in our application. +Phoenix поставляется с функцией **Live Reload**, которая автоматически обновляет приложение в браузере. Если сервер Phoenix все еще работал, то главная страница будет автоматически перезагружена и теперь должна отображать созданные только что кнопки. Посмотрите на результат, и с помощью них пользователи смогут свободно переходить на страницу определенного игрока в приложении. -## Writing Elixir Code +## Написание Elixir-кода -Lastly, let's get some experience with writing Elixir code in our templates -by converting our buttons to use embedded Elixir code instead of simple HTML. -The page will work the same way, but this will give us a chance to use a -Phoenix feature instead of writing HTML. +Наконец, давайте получим небольшой опыт написания кода на Elixir в шаблонах, использовав встроенный код Elixir для вывода кнопок вместо простого HTML. Страница будет выглядеть точно так же, но это даст нам возможность использовать возможность Phoenix вместо написания HTML. -Phoenix gives us a -[link](https://hexdocs.pm/phoenix_html/Phoenix.HTML.Link.html#link/2) function -we can use, and we can see a handful of examples provided in the documentation. +Phoenix предоставляет функцию [link](https://hexdocs.pm/phoenix_html/Phoenix.HTML.Link.html#link/2), которую мы можем использовать; на странице документации к этой функции можно увидеть несколько примеров использования. -Since we're working with a `.eex` file, that means we can embed Elixir code by -surrounding it with tags like this: `<%= ... %>`. The Elixir code that we put -inside those tags will be evaluated, and then rendered onto the page. +Поскольку мы работаем с файлом расширения `.eex`, это означает, что мы можем встроить код Elixir, окружив его тегами `<%= ... %>`. Код Elixir, который мы поместим в эти теги, будет выполнен, а затем выведен на страницу. -A helpful debugging technique while working with Elixir is to use the -[`IO.inspect`](https://hexdocs.pm/elixir/IO.html#inspect/2) function to display -results. In this example, we're using the `IO` module with the `inspect` -function, and we're passing it the string `"Hello World!"`: +При работе с Elixir полезной техникой отладки является использование функции [`IO.inspect`](https://hexdocs.pm/elixir/IO.html#inspect/2), чтобы отобразить результаты. В этом примере мы используем модуль `IO` с функцией `inspect` и передадим ей строку `"Hello World!"`: ```embedded_elixir
@@ -445,16 +337,11 @@ function, and we're passing it the string `"Hello World!"`:
``` -Let's take a look at the results in our browser: +Давайте посмотрим на результат в браузере: -![Embedded Elixir](images/diving_in/embedded_elixir.png) +![Встроенный код Elixir](images/diving_in/embedded_elixir.png) -We can do something similar to embed a link on our page. We won't need to -explicitly mention the module (`Phoenix.HTML.Link`), because we already have -access to some helpful Phoenix functions in this context. We can recreate -our existing HTML links with the following code by passing the link text, the -location, and a `button` class to make it look nice (Phoenix comes with a small -CSS framework preinstalled): +Мы можем сделать что-то подобное, чтобы вставить ссылку на нашу страницу. Нам не нужно явно указывать модуль (`Phoenix.HTML.Link`), потому что у нас уже есть доступ к некоторым полезным функциям Phoenix в данном контексте. Мы можем воссоздать наши существующие HTML-ссылки с помощью следующего кода, передав текст ссылки, адрес и CSS-класс кнопки, чтобы он выглядел хорошо (Phoenix поставляется с небольшим предустановленным CSS-фреймворком): ```embedded_elixir
@@ -463,22 +350,12 @@ CSS framework preinstalled):
``` -We can now verify that our links still work the same way they did previously: +Теперь мы можем убедиться, что наши ссылки по-прежнему работают так же, как и раньше: -![Link to Players Page Using Embedded Elixir](images/diving_in/updated_home_page.png) +![Ссылка по страницу игроков с использованием встроенного Elixir-кода](images/diving_in/updated_home_page.png) -## Summary +## Резюме -In this chapter, we managed to cover a lot of ground. We were able to create -the entire foundation for our application with a Phoenix back-end. We leveraged -the Phoenix generators to create our players resource, started getting an idea -of what the Phoenix folder structure looks like, and began editing files. We -also learned a little about routing and working with the database. +В этой главе нам удалось охватить много вопросов. Мы смогли создать фундамент для нашего приложения с помощью бэкенда на Phoenix. Мы использовали генераторы Phoenix для создания ресурса игроков, начали понимать, как выглядит структура директорий Phoenix, а также начали редактировать файлы. Кроме этого, немного узнали о маршрутизации и работе с базой данных. -We've gotten an introductory look at how to create a full Elixir and Phoenix -web platform, and we even created a couple of player records that we can use as -we continue building. But we moved quickly through these steps, and we don't -have a solid understanding of how all these pieces fit together yet. In the -next chapter, we'll delve into some Elixir basics. And instead of using -generators like we did in this chapter, we'll manually create features in our -application so we can continue increasing our experience. +Мы получили вводный взгляд на то, как создать полноценную веб-платформу с использованием Elixir и Phoenix, и даже создали пару записей об игроках, которые мы можем использовать, когда продолжим разработку. Но мы быстро прошли через все эти шаги, и у нас пока нет четкого понимания того, как все кусочки складываются в единую мозаику. В следующей главе мы углубимся в некоторые основы Elixir. И вместо того, чтобы использовать генераторы, как мы делали в этой главе, вручную создадим функциональность нашего приложения, чтобы продолжать увеличивать опыт. From b62afc93f3a73970a018b625d75d666c7a4a1fb5 Mon Sep 17 00:00:00 2001 From: Alexey Pyltsyn Date: Tue, 15 Jan 2019 09:46:38 +0300 Subject: [PATCH 05/10] diving_in: fixes --- manuscript/diving_in.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/manuscript/diving_in.md b/manuscript/diving_in.md index eabe332..9228f25 100644 --- a/manuscript/diving_in.md +++ b/manuscript/diving_in.md @@ -39,25 +39,25 @@ Fetch and install dependencies? [Yn] Y * running mix deps.get * running mix deps.compile * running cd assets && npm install && node node_modules/webpack/bin/webpack.js --mode development -``` -У нас все готово! Зайдите в приложение путем его запуска: +We are all set! Go into your application by running: $ cd platform -Затем настройте базу данных в файле `config/dev.exs` и выполните команду ниже: +Then configure your database in config/dev.exs and run: $ mix ecto.create -Запустите приложение на Phoenix следующим образом: +Start your Phoenix app with: $ mix phx.server -Вы также можете запустить приложение внутри IEx (Interactive Elixir) вот так: +You can also run your app inside IEx (Interactive Elixir) as: $ iex -S mix phx.server +``` -Phoenix отображает _много_ полезной информации. Во-первых, в выводе отображаются все сгенерированные файлы (не беспокойтесь, если на первый взгляд вывод кажется огромным; мы начнем только с нескольких этих файлов). Затем мы видим некоторую информацию о том, как настроить базу данных и запустить сервер. +Phoenix отображает _много_ полезной информации. Во-первых, в выводе отображаются все сгенерированные файлы (не беспокойтесь, если на первый взгляд вывод кажется огромным; мы начнем только с нескольких этих файлов). Затем мы видим информацию о том, как настроить базу данных и запустить сервер. ## Настройка базы данных From 08eeec8075069130916337354b56012d0dd02564 Mon Sep 17 00:00:00 2001 From: Alexey Pyltsyn Date: Wed, 16 Jan 2019 00:47:23 +0300 Subject: [PATCH 06/10] elixir_introduction: initial translation --- manuscript/elixir_introduction.md | 318 ++++++++---------------------- 1 file changed, 87 insertions(+), 231 deletions(-) diff --git a/manuscript/elixir_introduction.md b/manuscript/elixir_introduction.md index 778b202..c414625 100644 --- a/manuscript/elixir_introduction.md +++ b/manuscript/elixir_introduction.md @@ -1,23 +1,16 @@ -# Elixir Introduction +# Введение в Elixir -In the last chapter, we created a full Phoenix back-end platform. By default, -Phoenix applications contain a lot of Elixir code. But if we're just getting -started with the Elixir language, we should probably take a look at some simple -Elixir examples and get a better idea of how to work with the tools. +В предыдущей главе мы создали бэкенд-платформу на Phoenix. По умолчанию приложения Phoenix содержат много кода Elixir. Но если мы только начинаем работать с языком Elixir, нам, вероятно, стоит взглянуть на несколько простых примеров Elixir и лучше понять, как работать с инструментами. -## Creating an Elixir Project +## Создание Elixir-проекта -Let's create a small temporary project. We'll use the same `mix` tool that we -used in the last chapter when we created our Phoenix application, but this time -we're just creating a small Elixir project called `temporary`. Run the -following command in the Terminal: +Давайте создадим небольшой временный проект. Мы будем использовать тот же инструмент `mix`, который использовали в предыдущей главе, когда создавали наше приложение Phoenix, но на этот раз мы просто создаем маленький проект Elixir и назовём его `temporary`. Запустите следующую команду в терминале: ```shell $ mix new temporary ``` -The `mix` tool is a simple build tool that ships with Elixir. Here's what the -output should look like when we create our project: +Инструмент `mix` — это простой инструмент для сборки, поставляемый вместе с Elixir. Вот как должен выглядеть вывод при создании проекта: ```shell $ mix new temporary @@ -42,43 +35,31 @@ You can use "mix" to compile it, test it, and more: Run "mix help" for more commands. ``` -Let's change into the new project's directory and take a look at the files that -were generated for us: +Давайте перейдем в директорию нового проекта и посмотрим на созданные файлы: ```shell $ cd temporary ``` -The first thing you might notice is that our Elixir project and our Phoenix -project share a lot in common. The folder structure is similar: +Первое, что вы можете заметить — проект Elixir и проект на Phoenix имеют много общего. Структура директорий похожа: -![Elixir Folder Structure](images/elixir_introduction/elixir_folder_structure.png) +![Структура директорий Elixir](images/elixir_introduction/elixir_folder_structure.png) -The `platform` project we created in the last chapter contains more files and -folders, but it's important to note that it's still an Elixir project just like -the `temporary` one that we just created. The `config` folder contains -configuration settings, the `lib` folder is where we'll write most of our -Elixir code, and the `test` folder contains the tests that let us know our -application is working as intended. +Созданный в предыдущей главе проект `platform`, содержит больше файлов и директорий, но важно отметить, что это все еще проект Elixir, такой же, как `temporary`, который мы только что создали. Директория `config` содержит параметры конфигурации, папка `lib` — это там, где мы будем писать большую часть нашего кода на Elixir, а в директории `test` находятся тесты, которые позволяют нам удостовериться в том, что приложение работает так, как предполагалось. -## Elixir Testing +## Тестирование в Elixir -Depending on which programming languages you've worked with in the past, you -may have a lot of experience writing tests, or perhaps not. +Вне зависимости от того, с какими языками программирования вы работали в прошлом, у вас, возможно, есть большой опыт написания тестов. -If you haven't written tests before, the basic idea is that tests give us a way -to feel confidence that our code is actually working as expected. We write our -expectations (or "assertions"), and they give us a quick way to check that the -code we're writing works (and doesn't break other code). We'll delve deeper -into testing with our Phoenix app later, but for now let's just try it out. +Если ранее вы не писали тесты, основная идея является то, что тесты дают возможность почувствовать уверенность в том, что код действительно работает так, как ожидалось. Мы пишем наши предположения (или «утверждения»), которые дают нам быстрый способ проверить, работает ли должным образом написанный нами код (и не нарушает ли он работу другого кода). Позже мы углубимся в тестирование с нашим приложением Phoenix, но сейчас давайте просто попробуем тесты в действии. -Run the `mix test` command inside the `temporary` folder: +Запустите команду `mix test` внутри директории `temporary`: ```shell $ mix test ``` -The output should look something like this: +Вывод должен быть примерно таким: ```shell $ mix test @@ -92,17 +73,11 @@ Finished in 0.03 seconds Randomized with seed 670956 ``` -## Elixir Compilation +## Компиляция Elixir -Here's where we'll start to see some key features of Elixir. First, we can see -that Elixir is a _compiled_ language. The first time we run our code after -making changes, Elixir needs to compile it to Erlang bytecode. This can be really -helpful because it means we'll catch errors early instead of having to debug our -app while we're using it. +В этом разделе мы начнем знакомиться с некоторыми ключевыми особенностями Elixir. Во-первых, мы увидим, что Elixir — это _компилируемый_ язык. Когда мы в первый раз запускаем наш код после внесения изменений, Elixir должен скомпилировать его в байт-код Erlang. Это может быть очень полезно, потому что означает, что мы скорее будем отлавливать ошибки, чем отлаживать приложение время его использования. -In fact, if we run the `mix test` command again, we'll see that Elixir doesn't -need to recompile the code because we haven't made any changes (note the line -about compiling files is now missing): +На самом деле, если мы снова запустим команду `mix test`, то увидим, что Elixir не нужно перекомпилировать код, потому что мы не внесли никаких изменений (обратите внимание, что строка о компиляции файлов теперь отсутствует): ```shell $ mix test @@ -114,15 +89,11 @@ Finished in 0.03 seconds Randomized with seed 114557 ``` -## Elixir Modules and Functions +## Модули и функции Elixir -The Elixir code that we'll write in this project is contained in the -`lib/temporary.ex` file. Files that end in `.ex` are Elixir files that will be -compiled and run (you'll also notice that we have files that end in `.exs`, -which are Elixir scripts). +Код Elixir, который мы напишем в этом проекте, находится в файле `lib/temporary.ex`. Файлы с расширением `.ex` — это файлы Elixir, которые будут скомпилированы и запущены (вы также заметите, что у нас есть файлы с расширением `.exs`, представляющие собой скрипты Elixir). -Inside the `lib/temporary.ex` file, we see the basic structure for _all_ the -Elixir programs that we'll be writing. +Внутри файла `lib/temporary.ex` мы видим базовую структуру для _всех_ программ Elixir, которые мы будем писать. ```elixir defmodule Temporary do @@ -145,7 +116,7 @@ defmodule Temporary do end ``` -We start out with a **module** that encapsulates our related code: +Начнем с **модуля**, который инкапсулирует соответствующий код: ```elixir defmodule Temporary do @@ -153,8 +124,7 @@ defmodule Temporary do end ``` -If we ignore the documentation for now, we'll see that we have one -**function**: +Если пока игнорировать комментарии с документацией, мы увидим одну **функцию**: ```elixir def hello do @@ -162,15 +132,13 @@ def hello do end ``` -Inside that function, we have our **return value**: +Внутри этой функции есть **возвращаемое значение**: ```elixir :world ``` -Let's start making some changes. Rename the `hello` function to `add`. We'll -pass two parameters (`x` and `y`), and we'll return the addition of these two -values using `x + y` inside the function: +Давайте начнем вносить некоторые изменения. Переименуйте функцию `hello` на `add`. Передадим два параметра (`x` и `y`) и вернем сложение этих двух значений, используя выражение `x + y` внутри функции: ```elixir def add(x, y) do @@ -178,14 +146,11 @@ def add(x, y) do end ``` -## Functions, Tests, and Documentation +## Функции, тесты и документация -The example above is admittedly simple, but it's good in the sense that we -know how to create a function now. But how do we use it? +Приведенный выше пример, конечно, простой, но он хорош потому что мы теперь знаем, как создать функцию. Но каким образом мы будем их использовать? -We generally use the `Module.function(arguments)` syntax to invoke the -functions we've declared. If we look at the original documentation for our -`hello` function, we can see the example usage: +Как правило, мы используем синтаксис вида `Module.function(arguments)` для вызова объявленных функций. Если мы посмотрим на изначальную документацию для нашей функции `hello`, то увидим пример использования: ```elixir defmodule Temporary do @@ -208,18 +173,13 @@ defmodule Temporary do end ``` -This tells us that we should be able to run `Temporary.hello()` and it should -return `:world`. This is where things get interesting, so let's run `mix test` -again: +Часть комментария с примером использования указывает на то, что если мы выполним строчку кода `Temporary.hello()`, то она вернет `:world`. Вот тут начинается самое интересное, поэтому давайте снова запустим `mix test`: ```shell $ mix test ``` -Since we no longer have our `hello` function, it's not surprising that our -tests failed. But we actually have _two_ test failures. One of them is from the -test file located in the `test` folder, but the other failure is actually -coming from the example in our documentation (which is called a **doctest**). +Поскольку больше нет функции `hello`, неудивительно, что тесты не прошли. На самом деле у нас _два_ неудачных теста. Один из них взят из тестового файла в директории `test`, в то время как другой в действительности взялся из примера использования в документации (который называется **doctest**). ```shell $ mix test @@ -247,8 +207,7 @@ Finished in 0.04 seconds Randomized with seed 520513 ``` -Let's update the documentation so it shows an example of how to use our new -`add` function: +Давайте обновим документацию, чтобы она отражала реальный пример использования новой функции `add`: ```elixir defmodule Temporary do @@ -271,8 +230,7 @@ defmodule Temporary do end ``` -We can run our tests again, and the doctest example in our `lib/temporary.ex` -file should now be passing: +Можно снова запустить тесты, и на этот раз доктест в `lib/temporary.ex` должен пройти: ```shell $ mix test @@ -294,15 +252,11 @@ Finished in 0.03 seconds Randomized with seed 682227 ``` -Doctests are an _awesome_ feature of Elixir. They allow us to write our -functions _and_ document them _and_ test that they work all at once! It -encourages us to write and maintain our documentation, and gives us confidence -that our code is actually doing what we think it is. +Доктесты — потрясающая _возможность_ Elixir, позволяющая нам одновременно _и_ документировать, _и_ проверять работу функции! Это вдохновляет нас писать и поддерживать документацию, а также придает уверенность в том, что наш код действительно делает то, что мы задумали. -## Writing Tests +## Написание тестов -Let's write a few tests to ensure that our `add` function is working as -intended. Open the `test/temporary_test.ex` file and add the following: +Давайте напишем несколько тестов, чтобы убедиться, что наша функция добавления работает так, как должна. Откройте файл `test/temporary_test.ex` и добавьте следующий код: ```elixir defmodule TemporaryTest do @@ -327,23 +281,11 @@ defmodule TemporaryTest do end ``` -Looking at the `test/temporary_test.exs` file, note that the test code still -takes the same general format we used in `lib/temporary.ex`, where we have a -module defined at the top that encapsulates the rest of our code. We also see -that we're using the default [`ExUnit`](https://hexdocs.pm/ex_unit/ExUnit.html) -library to write our tests. Then, there's the `doctest Temporary` line, which -is how the tests knew to run the examples we were writing in our documentation. +Рассмотрите содержимое файла `test/temporary_test.exs` и обратите внимание, что тестовый код по-прежнему имеет тот же общий формат, который мы использовали в `lib/temporary.ex`, где у нас есть определение модуля в самом вверху, содержащий остальную часть кода. Мы также видим, что используем стандартную библиотеку [`ExUnit`](https://hexdocs.pm/ex_unit/ExUnit.html) для написания тестов. Кроме этого, есть строчка `doctest Temporary`, чтобы тесты знали, как выполнять примеры, написанные в документации. -The three `test` cases show basic examples of how we can call our function with -some example numbers and verify that the result is correct. For example, -passing `1` and `1` as arguments to our `add` function should return a result -of `2`. There are other -[assertions](https://hexdocs.pm/ex_unit/ExUnit.Assertions.html) that `ExUnit` -provides, but we'll stick with `assert` for now to ensure that we're getting a -`true` value from our tests. +В трех тестовых сценариев (`test`) показаны простые примеры того, как мы можем вызывать функцию с некоторыми примерами чисел и проверять правильность результата. Например, передача `1` и `1` в качестве аргументов функции `add` должна вернуть результат `2`. Есть и другие [утверждения](https://hexdocs.pm/ex_unit/ExUnit.Assertions.html), предоставляемые `ExUnit`, но пока мы остановимся на `assert` с целью проверить на значение `true` в наших тестах. -We should be able to run our tests again and see that all three of these test -cases are passing (and the doctest is still passing as well): +Теперь, если мы снова запустим тесты, то увидим, что все три из этих тестовых вариантов проходят (включая и доктест): ```shell $ mix test @@ -357,22 +299,15 @@ Randomized with seed 867380 ## IEx -How would we run our code in an interactive environment? The tests are doing a -good job of testing values, but what if something wasn't working the way we had -expected? Let's run the following command from inside our `temporary` project -folder: +Как бы нам запустить код в интерактивной среде? Тесты хорошо подходят для проверки значений, но что, если что-то не работает так, как мы ожидали? Давайте запустим следующую команду из директории проекта `temporary`: ```shell $ iex -S mix ``` -This allows us to run Elixir code in an interactive environment and see the -results (you can also just use `iex` from the command line to get started, but -using `iex -S mix` is preferable because it means we don't have to manually -import the modules we want to work with). +Эта команда позволяет запускать код Elixir в интерактивной среде и просматривать результаты (вы также можете использовать просто `iex` из командной строки для начала, но использование `iex -S mix` предпочтительнее, поскольку тогда нам не нужно вручную импортировать модули, с которыми мы хотим работать). -Here's an example where we are basically recreating our first `test` case to -call the `add` function from the `Temporary` module and see the result: +Вот пример, где мы в основном повторяем наш первый тестовый случай, который вызывает функцию `add`, определенную в модуле `Temporary`, чтобы увидеть такой результат: ```elixir $ iex -S mix @@ -381,30 +316,20 @@ iex(1)> Temporary.add(1, 1) 2 ``` -We can try our second example case too: +Мы также можем попробовать второй тестовый пример: ```elixir iex(2)> Temporary.add(1.5, 1.5) 3.0 ``` -Everything works as expected in the tests, and now we have an interactive way -of checking our code too. Feel free to tinker around with writing some Elixir -code in the interactive environment, and then press `Control + C` twice on your -keyboard when you're ready to exit. +В тестах все работает как ожидается, а теперь мы еще узнали про интерактивный способ проверки кода. Не стесняйтесь писать какой-нибудь Elixir-кода в интерактивной среде, а затем дважды нажмите сочетание клавиш `Control + C`, когда захотите выйти. -## The Pipe Operator +## Оператор конвейера -Our third `test` case uses a common pattern seen in programming. We break up our -code into small chunks, and we assign the values to variables. This has a great -benefit of being able to name things in obvious ways, but Elixir has an -alternative approach that helps us reconsider the way we write code. +В нашем третьем тесте используется распространенная модель программирования — мы разбиваем код на маленькие фрагменты и присваиваем значения переменным. Такой подход имеет большое преимущество, связанный с возможностью именования очевидными способами, но в Elixir есть альтернативный подход, помогающий нам пересмотреть метод написания кода. -The idea behind the "pipe operator" (`|>`) is that it encourages us to think -about our functions in terms of data transformation. Instead of using -variables, we take an initial value, pipe it through a handful of functions, -and return the result at the end. Let's take another look at our third `test` -case: +Идея «оператора конвейера» (`|>`) заключается в том, что он стимулирует нас думать о функциях с точки зрения преобразования данных. Вместо использования переменных, мы берем начальное значение, передаем его через небольшое количество функций и в конце возвращаем результат. Давайте еще раз посмотрим на третий сценарий: ```elixir test "the add function returns a number" do @@ -414,9 +339,7 @@ test "the add function returns a number" do end ``` -This example was intentionally written with extraneous variables that aren't -particularly necessary. Let's use the pipe operator syntax, keeping in mind -that the code is still going to accomplish the same thing: +Этот пример намеренно написан, используя дополнительные переменные, которые не особенно нужны. Давайте вместо этого воспользуемся синтаксисом оператора конвейера, с учетом того, что код все еще делает то же самое: ```elixir test "the add function returns a number" do @@ -426,12 +349,9 @@ test "the add function returns a number" do end ``` -Whoa. What's happening here? Instead of using variables, we're evaluating a -result and then using the `|>` to pass it along as the argument to the next -function. +Вау! И что здесь происходит? Вместо того, чтобы использовать переменные, мы сначала вычисляем результат, а затем используем `|>` для передачи его как аргумент следующей функции. -It also enables us to take the data and "pipe it through" other functions. For -example, let's inspect what value is getting passed to `assert` at the end: +Данный оператор также позволяет получать данные и передавать их другим функциям. Например, давайте проверим, какое значение передается `assert` в конце: ```elixir test "the add function returns a number" do @@ -442,7 +362,7 @@ test "the add function returns a number" do end ``` -We can run `mix test` from the command line to see the results: +Можно выполнить `mix test` из командной строки, чтобы увидеть результаты: ```shell $ mix test @@ -455,18 +375,13 @@ Finished in 0.03 seconds Randomized with seed 312071 ``` -That explains why our test is passing, because `true` is getting passed to the -`assert` function. +Это объясняет, почему тест проходит, поскольку `true` передается в функцию `assert`. -## More Piping +## Больше конвейерной обработки -These are simple examples, because these functions each expect a single -argument. But what if we want to pipe to a function that takes multiple -arguments? When we use the pipe operator in Elixir, it pipes the value as the -_first_ argument in the next function. +Это простые примеры, потому что каждая из этих функций по одному аргументу. Но что, если мы хотим передать функцию, принимающая несколько аргументов? При использовании оператора конвейера в Elixir, он передает значение в качестве _первого_ аргумента в следующую функцию. -In other words, we could actually refactor our test case to pass the first -value like this: +Другими словами, мы могли бы изменить код теста с целью передать первое значение, как показано ниже: ```elixir test "the add function returns a number" do @@ -478,13 +393,9 @@ test "the add function returns a number" do end ``` -This demonstrates that we can pipe the value `1.5` to the `Temporary.add` -function, and it will use the value as the _first_ argument. And `3.5` will be -sent as the _second_ argument to the `Temporary.add` function. +Обновленный код теста демонстрирует, что мы можем передать значение `1.5` в функцию `Temporary.add`, и данное значение будет использоваться в качестве _первого_ аргумента, когда как значение `3.5` будет передано _вторым_ аргументом функции `Temporary.add`. -Before we move on, let's go back to the original pipe operator example since it -was cleaner code. But the examples above are an important demonstration of how -we can use the pipe operator. +Прежде чем мы продолжим, давайте вернемся к изначальному примеру оператора конвейера, поскольку это более чистый код. Но приведенные выше примеры являются важной демонстрацией того, как мы можем использовать оператор конвейера. ```elixir test "the add function returns a number" do @@ -494,31 +405,19 @@ test "the add function returns a number" do end ``` -## Function Arity +## Арность функций -In this book, we've referred to functions like the `add` function as simply -`add`. But functions in Elixir are often referred to in terms of their "arity". +В этой книге мы обращались к таким функциям (например, функция `add`), как просто `add`. Но функции в Elixir часто дают обозначают в соответствии с их «арностью». -The arity of a function is the number of arguments it takes. In our examples -above, the `add` function takes two arguments, so it would be referred to as -`add/2`. The `is_number` function only takes a single argument, so we -would refer to it as `is_number/1`. +Арность функции — это количество аргументов, которые она принимает. В вышеприведенных примерах функция `add` принимает два аргумента, поэтому она будет именоваться в тексте `add/2`. Функция `is_number` принимает только один аргумент, поэтому мы бы ее именовали как `is_number/1`. -For the rest of the book, we'll try to be consistent about referring to -functions with their arity included, because the arity is of particular -importance in the Elixir language. In fact, we can define multiple functions -that share the same name, but behave differently depending on the number of -arguments we pass to them. This can be a tricky concept at first, but we'll see -some examples soon that should help to clarify. +В остальной части книги с целью соблюдения единообразия, мы будем ссылаться на функции, учитывая их арность, поскольку она имеет особое значение в языке Elixir. Кстати, мы можем определить несколько функций с одним и тем же именем, но с различным поведением в зависимости от количества переданных аргументов. Поначалу это может показаться сложной концепцией, однако вскоре мы увидим несколько примеров, которые помогут прояснить эту идею. -## Shorthand Function Syntax +## Сокращенный синтаксис определения функции -At this point, we're probably dying to get back to Phoenix and build our -application. But there are just a couple more Elixir topics that will help -us when we start looking at our Phoenix code. Without knowing the concepts -behind Elixir, it can be tough to really understand what's going on in Phoenix. +На данный момент мы, вероятно, очень хотим вернуться в Phoenix и разрабатывать наше приложение. Но есть еще пара тем из Elixir, которые помогут нам в изучении код на Phoenix. Не зная концепций, лежащих в основе Elixir, в действительности сложно понять, что происходит в Phoenix. -The functions we've seen so far take the following format: +Функции, которые мы видели до сих пор, имели следующий формат: ```elixir def function_name(arguments) do @@ -526,70 +425,45 @@ def function_name(arguments) do end ``` -When we're dealing with small, simple functions like `add/2`, we can make our -code more concise and readable by using the shorthand function syntax: +Когда мы имеем дело с небольшими простыми функциями, такими как `add/2`, возможно сделать код более кратким и читаемым, если использовать сокращенный синтаксис объявления функции: ```elixir def function_name(arguments), do: ... ``` -Note that there are extra `,` and `:` characters, but this enables us to remove -the `end` keyword and move our entire function definition to a single line. +Обратите внимание, что есть дополнительные символы `,` и `:`, использование которых позволит нам удалить ключевое слово `end` и написать все тело функции в одну строку. -Here's our `add/2` function as a single line. You can update our example in the -`lib/temporary.ex` file and then run `mix test` again to verify that it still -works. +Ниже функция `add/2`, написанная в виде одной строки. Вы можете обновить пример в файле `lib/temporary.ex`, а затем снова запустить команду `mix test`, чтобы убедиться, что он все еще работает. ```elixir def add(x, y), do: x + y ``` -There aren't strict rules about when you should use shorthand function syntax. -On the one hand, it's good practice to break up our programs into small -functions that are easy to reason about, which could mean many of our functions -fit well on a single line. However, we shouldn't feel compelled to force -multiline functions to fit on a single line arbitrarily. The reason we're -introducing this concept now is that the `add/2` function will be easier to -visualize and reason about in the next section when using the shorthand -function syntax. +Нет строгих правил относительно того, когда нужно использовать сокращенный синтаксис объявления функции. С одной стороны, хорошая практика — разделять программы на небольшие функции, которые становятся легче для понимания, а это значит, что многие функции хорошо вписываются в одну строку. Однако вам необязательно стремится писать многострочные функции в одну строку. В данный момент мы знакомимся с этой концепцией, потому что функцию `add/2` будет проще визуально представить и объяснять в следующем разделе при использовании сокращенного синтаксиса определения функции. -## Pattern Matching +## Сопоставление с образцом -The reason for introducing shorthand function syntax here is that it gives us -a more obvious way to see one of Elixir's most powerful features in action: -pattern matching. +Причина применения сокращенного синтаксиса определения функции — это более очевидный способ узнать одну из самых мощных возможностей Elixir в действии: сопоставление с образцом. -Pattern matching can be difficult to comprehend at first, so be gentle with -yourself if it takes some time to understand. It's one of those things that -needs to be seen and experienced a couple of times before it starts to sink in. +Поначалу метод сопоставления с образцом может быть трудным для понимания, поэтому будьте нежны с самим собой, если потребуется какое-то время для понимания. Это одна из тех тем, которую нужно увидеть и испытать пару раз, прежде чем ее поймешь. -Elixir allows us to create multiple "clauses" of our functions. That means we -can create a new clause of our `add/2` function, and Elixir will use pattern -matching to determine which clause actually gets used when the function is -called. It sounds confusing, so let's see an example. +Elixir позволяет нам создавать несколько «условий» функций. Это означает, что можно создать новое условие для функции `add/2`, и тогда Elixir будет использовать сопоставление с образцом для определения, какое из условий нужно использовать при вызове функции. Это звучит странно, поэтому давайте рассмотрим пример. -When we add `0` to a number, the result is actually just the number itself -(this is known as _the identity property of addition_). So `0 + 1` should -return a result of `1`. When we use the `add/2` function, it would look like -this: +Когда мы добавляем `0` к числу, фактически результатом является просто само число (это еще известно как _тождественное свойство сложения_). Так что выражение `0 + 1` должно вернуть результат `1`. При использовании функции `add/2`, такой случай использования будет таким: ```elixir iex> Temporary.add(0, 1) 1 ``` -That means whenever we pass `0` as an argument to our function, we don't really -need to perform any addition. We can add a new clause for our `add/2` function -that handles cases where the first argument is `0`: +Это означает, что всякий раз, когда мы передаем `0` в качестве аргумента функции, нам не нужно выполнять каких-либо операций сложения. Можно добавить новое условие для нашей функции `add/2`, которая обрабатывает случаи, когда первый аргумент равен `0`: ```elixir def add(0, y), do: y def add(x, y), do: x + y ``` -On the first line, we're basically just ignoring the `0` argument and returning -the value of `y` for the result. Next, we can do the same thing when the second -argument is `0`: +В первой строчке мы просто игнорируем аргумент `0` и возвращаем значение `y` как результат. Далее можно сделать аналогичное, когда второй аргумент равен `0`: ```elixir def add(0, y), do: y @@ -597,9 +471,7 @@ def add(x, 0), do: x def add(x, y), do: x + y ``` -On the second line, we ignore the `0` argument again and just return the value -of `x` for the result. Next, we can even add another clause that "matches" for -when both arguments are `0`s: +Во второй строчке мы снова игнорируем аргумент `0` и просто возвращаем значение `x`. Далее, мы можем даже добавить еще одно условие, которое «соответствует», когда оба аргумента представлены значением `0`: ```elixir def add(0, 0), do: 0 @@ -608,8 +480,7 @@ def add(x, 0), do: x def add(x, y), do: x + y ``` -And here's our full example with a few more doctests to verify that everything -is working as expected: +И, наконец, полная версия примера с несколькими дополнительными доктестами для проверки того, что все работает как ожидается: ```elixir defmodule Temporary do @@ -641,17 +512,13 @@ defmodule Temporary do end ``` -## Guards +## Ограничители -Lastly, Elixir allows us to add "guard clauses" to our functions to make sure -they're working with the right values. +Наконец, Elixir позволяет нам добавлять «операторы-ограничители» в функциях, чтобы убедиться, что они работают с правильными значениями. -Our `add/2` function is only designed to work with numbers. They can be integers -or floating point numbers, but we don't want to add strings together (string -concatenation would actually require the use of the `<>` operator). +Функция `add/2` предназначена только для работы с числами. Они могут быть целыми числами или числами с плавающей запятой, но мы не хотим добавлять строки вместе (конкатенация строк фактически потребует использования оператора `<>`). -We can use the `when` keyword along with the `is_number/1` function we saw -previously to make sure that our function is working with numerical values. +Мы можем использовать ключевое слово `when` вместе с функцией `is_number/1`, которую мы видели ранее, для того, чтобы указать, что данная функция работает только с числовыми значениями. ```elixir def add(0, 0), do: 0 @@ -660,10 +527,7 @@ def add(x, 0) when is_number(x), do: x def add(x, y) when is_number(x) and is_number(y), do: x + y ``` -Functions like `is_number/1` can be really helpful to check the types of values -we're working with. One helpful tip is to find similar functions available to -us using `iex`. Inside `iex`, type `is_` and then hit the TAB key on your -keyboard, and it will display the different checks that are available: +Такие функции, как `is_number/1`, могут быть очень полезны для проверки типов значений, с которыми мы работаем. Один полезный совет — найти похожие функции, доступные с помощью `iex`. Внутри `iex` введите `is_`, а затем нажмите клавишу TAB и она отобразит различные доступные проверки: ```elixir $ iex @@ -675,22 +539,14 @@ is_list/1 is_map/1 is_nil/1 is_number/1 is_pid/1 is_port/1 is_reference/1 is_tuple/1 ``` -## Summary +## Резюме -This chapter was intended to give a brief introduction to Elixir concepts. These -will be invaluable as we start building our Phoenix applications, because we'll -see that Phoenix code is really just Elixir code. Without some background in -Elixir, it can occasionally be difficult to understand what's going on. +Эта глава предназначена, чтобы дать краткое введение в концепции Elixir. Они будут неоценимы, когда мы начнем создавать приложения с помощью Phoenix, потому что мы увидим, что код Phoenix +— это на самом деле просто код на Elixir. Без некоторого опыта в Elixir иногда бывает трудно понять, что же происходит. -This was not meant as exhaustive introduction to Elixir. There are many more -concepts, and there are several books available that give a full introduction -to the language. In this book, we're going to keep moving because our goal is -to build a practical real-world application, and we'll learn what we need along -the way. But check out these free resources if you want to get a little -more Elixir experience before continuing: +Текущая глава не задумывалась как исчерпывающее введение в Elixir. Есть еще много концепций, а также несколько книг, которые дают полное введение в язык. В этой книге мы продолжим двигаться дальше, потому что наша цель — создать реальное практическое приложение. Однако обратите внимание на бесплатные ресурсы ниже, если вы хотите получить немного больше опыта с Elixir, перед тем, как продолжить: -- [Elixir Getting Started Guide](http://elixir-lang.org/getting-started/introduction.html) -- [Elixir School](https://elixirschool.com/en/lessons/basics/basics) +- [Руководство по началу работы с Elixir (на англ.)](http://elixir-lang.org/getting-started/introduction.html) +- [Elixir School](https://elixirschool.com/ru/lessons/basics/basics) -Feel free to delete the `temporary` project, and in the next chapter we'll -continue working towards building our platform application. +Можете спокойно удалить временный проект `temporary`, а в следующей главе мы продолжим работу по созданию приложения для игровой платформы. From 894d0ca93e2d2487a29e387de98e9c5f5c281f11 Mon Sep 17 00:00:00 2001 From: Alexey Pyltsyn Date: Thu, 17 Jan 2019 10:03:02 +0300 Subject: [PATCH 07/10] phoenix_testing_and_deployment: initial translation --- manuscript/phoenix_testing_and_deployment.md | 249 +++++-------------- 1 file changed, 69 insertions(+), 180 deletions(-) diff --git a/manuscript/phoenix_testing_and_deployment.md b/manuscript/phoenix_testing_and_deployment.md index b10bae2..67bd511 100644 --- a/manuscript/phoenix_testing_and_deployment.md +++ b/manuscript/phoenix_testing_and_deployment.md @@ -1,21 +1,12 @@ -# Phoenix Testing and Deployment +# Тестирование и развертывание в Phoenix -Now that we have some familiarity with Elixir, let's get back to our Phoenix -application. In this chapter, we're going to be working with Phoenix tests, -GitHub version control, and Heroku deployment. +Теперь, когда мы немного познакомились с Elixir, давайте вернемся к нашему Phoenix-приложению. В этой главе мы будем работать с тестами Phoenix, сервисом по размещению git-репозиториев GitHub и развертыванием с помощью Heroku. -If you're already familiar with these concepts and only want to work locally -for this project, feel free to skim through the content. Even if you decide to -skip the Heroku deployment, the concepts here are important. Keeping our tests -passing and consistently checking in our code contributes to a sane development -workflow. +Если вы уже знакомы со всем перечисленным и предпочитаете сейчас работать над проектом только локально, то не стесняйтесь бегло просмотреть эту главу. Даже если вы решите пропустить раздел про развертывание на Heroku, рассматриваемые здесь концепции имеют важное значение. Поддержание тестов в рабочем состоянии и постоянная проверка кода способствуют нормальному рабочему процессу разработки. -## Running Phoenix Tests +## Запуск тестов Phoenix -In the last chapter, we learned that we could use the `mix test` command to run -the tests for our simple Elixir project. We can do the same thing for our -Phoenix project. Let's go to our `platform` folder and run `mix test` (the -results below have been cleaned up for readability): +В предыдущей главе мы узнали, что можем использовать команду `mix test` для выполнения тестов в нашем простом проекте на Elixir. Мы можем сделать аналогичное и для нашего Phoenix-проекта. Давайте перейдем в директории `platform` и выполним команду `mix test` (приведенные ниже результаты были сокращены для удобства чтения): ```shell $ mix test @@ -36,13 +27,9 @@ Finished in 0.2 seconds Randomized with seed 905 ``` -The good news is it looks like we already have 19 tests. Some of them came with -Phoenix by default when we ran `mix phx.new platform`. Other tests were created -when we ran the `mix phx.gen.html` generator for our players resource. +Хорошая новость в том, что у нас уже есть 19 тестов. Некоторые из уже были вместе с Phoenix по умолчанию, когда мы выполнили `mix phx.new platform`. Другие тесты были созданы, когда мы запустили генератор `mix phx.gen.html` для нашего ресурса игроков. -The bad news is one of our tests is no longer passing due to the changes we -made to our home page. Let's take a look at the -`test/platform_web/controllers/page_controller_test.exs` file: +Плохая новость — один из тестов больше не проходит из-за изменений, внесенных в домашнюю страницу. Давайте откроем файл `test/platform_web/controllers/page_controller_test.exs`: ```elixir defmodule PlatformWeb.PageControllerTest do @@ -55,22 +42,11 @@ defmodule PlatformWeb.PageControllerTest do end ``` -It looks like this test is making an HTTP `get` request to the default route -(`"/"`). If we look at the `http://localhost:4000/` URL, you can think of that -trailing slash as the default `/` route. +Похоже, этот тест отправляет HTTP-запрос типа `get` на маршрут по умолчанию (`"/"`). Если посмотреть на URL-адрес `http://localhost:4000/`, можно подумать, что завершающий слеш используется для маршрута по умолчанию — `/`. -Our test is expecting the text `"Welcome to Phoenix!"` to appear somewhere on -the page, but remember that we replaced the default Phoenix page. +Наш тест ожидает, что текст `"Welcome to Phoenix!"` появится где-то на странице, но если вы помните, то мы заменили страницу по умолчанию Phoenix. -Keep in mind that we don't need a full understanding of everything going on in -the tests yet. For now, we just want to get back to where all the tests are -passing. In this case, a quick fix is to assert that the home page contains the -word `"Players"` instead of `"Welcome to Phoenix!"`. This is admittedly a -brittle test that's subject to break when we make changes to our home page, but -since we're making a game platform, it's likely that our home page is going to -say `"Players"` somewhere, and this test still allows us to ensure that our -home page is loading properly. Let's go ahead and update our test with the -following: +Имейте в виду, что нам пока не нужно полное понимание всего, что происходит в тестах. Сейчас мы просто хотим вернуться к тому моменту, когда проходят все тесты. В этом случае быстрое исправление состоит в том, чтобы проверить, что домашняя страница содержит слово `"Players"` вместо `"Welcome to Phoenix!"`. Надо признать, это хрупкий тест, который можно сломать, когда мы в следующий раз внесем изменения в домашнюю страницу, но, поскольку мы создаем игровую платформу, вполне вероятно, что на домашней странице где-то будет слово `"Players"`, и такой тест все еще позволяет нам гарантировать, что домашняя страница загружается правильно. Давайте продолжим и обновим наш тест следующим: ```elixir defmodule PlatformWeb.PageControllerTest do @@ -83,7 +59,7 @@ defmodule PlatformWeb.PageControllerTest do end ``` -We can run our tests again, and we should see all green: +Мы можем заново запустить тесты, и мы увидим окрашенным в зеленый цвет вывод: ```shell $ mix test @@ -95,18 +71,13 @@ Finished in 0.3 seconds Randomized with seed 187055 ``` -## Git and GitHub +## Git и GitHub -Now that all our tests are passing and our application is in working condition, -let's go ahead and commit what we have so far and push it to GitHub. +Теперь, когда все наши тесты успешно проходят, а приложение находится в рабочем состоянии, давайте пойдем дальше и зафиксируем всё то, что у нас есть, и разместим это на GitHub. -We won't cover version control in detail in this book, and you're welcome to -skip the parts with `git` commands if you'd like. But it's a good idea to keep -a history of your project so you can always recover from mistakes. This will -also help when it comes time to deploy our application to Heroku. +В этой книге мы не будем подробно касаться темы управления версиями, и вы можете пропустить части, связанные с командами `git`, если хотите. Но это хорошая идея по хранению истории вашего проекта таким образом, что вы всегда могли восстановиться от ошибок. Система контроля версиями также пригодиться, когда придет время развернуть приложение на Heroku. -If you have [Git](https://git-scm.com/) installed, run the following commands -inside the `platform` folder to commit what we have so far: +Если у вас установлен [Git](https://git-scm.com/), выполните следующие команды в директории `platform`, чтобы зафиксировать (добавить в систему управления версиями) все файлы, которые у нас есть на текущий момент: ```shell $ git init @@ -114,50 +85,34 @@ $ git add . $ git commit -m "Initial Phoenix platform application" ``` -If you have a GitHub account, you can create a new public repository at -https://github.com/new. Give it the name `platform`, and then the following -commands will allow us to push our local application to GitHub (you'll need to -add your username on the first line): +Если у вас есть аккаунт на GitHub, вы можете создать новый публичный репозиторий по адресу https://github.com/new. Присвойте ему имя `platform`, а затем выполните следующие команды, которые отправят код приложения на GitHub (вам нужно заменить `YOUR-GITHUB-USERNAME` на ваш логин в первой строчке): ```shell $ git remote add origin https://github.com/YOUR-GITHUB-USERNAME/platform.git $ git push -u origin master ``` -Keep in mind that the audience for this book is expected to have some experience -with these topics already. Feel free to take your time, skim quickly, or skip -ahead as needed. +Имейте в виду, что у читателей этой книги, как предполагается, уже есть определенный опыт работы с вышеописанными темами. Не волнуйтесь по поводу потраченного время, читайте по диагонали, или вовсе пропустите данное описание при необходимости. ## Heroku -For those that haven't used [Heroku](https://www.heroku.com) before, it -essentially gives us an easy and free way to deploy our application and see it -running live. +Для тех, кто не использовал Heroku ранее — этот сервис по факту дает нам простой и бесплатный способ развернуть приложение и запустить его в работу в онлайн-режиме. -It's not always an ideal deployment environment for Elixir applications, but -it's perfect for our purposes, because we're just looking for the simplest way -to get our application up and running. +Данный сервис не всегда подходит для развертывания приложений на Elixir, но он идеально подходит для наших целей, поскольку мы просто ищем наиболее простой способ запустить в продакшен наше приложение. -Sign up for a Heroku account if you haven't already, and then our deployments -will be as simple as running `git push heroku master` when we're ready. +Зарегистрируйте аккаунт Heroku, если вы еще этого не сделали, и после этого, развертывание приложение будет таким простым, как и запуск `git push heroku master` , когда мы будем готовы. -## Heroku Setup +## Настройка Heroku -After you've signed up for a Heroku account, create a free app using their web -interface (the name `platform` will already be taken, so you'll have to come up -with a name you like or allow Heroku to choose a random name for you). Then, -download the [Heroku toolbelt](https://toolbelt.heroku.com) command line tool. +Как только вы зарегистрировались в Heroku, создайте бесплатное приложение с помощью веб-интерфейса сервиса (имя `platform` в качестве приложения уже будет занято, поэтому нужно придумать имя, которое вам нравится, либо позволить Heroku выбрать случайное имя за вас). Затем загрузите инструмент командной строки [Heroku toolbelt](https://toolbelt.heroku.com). -Once you have that installed, you can run the `heroku login` command to sign in -to your account. Since we have an existing Git repository, we can use the -following command to add our application to Heroku: +После того, как вы установили данную утилиту, можно запустить команду `heroku login`, чтобы войти в собственный аккаунт. Так как у нас есть существующий Git-репозиторий, мы можем использовать приведенную команду ниже для добавления приложения на Heroku: ```shell $ heroku git:remote -a YOUR-HEROKU-APP-NAME ``` -Now inside our `platform` folder, we can run the `git remote` command and see -that we now have two remotes for our project: +Теперь в нашей директории `platform`, если мы выполним команду `git remote`, то увидим, что теперь у нас есть два удаленных репозитория в нашем проекте: ```shell $ git remote @@ -165,22 +120,16 @@ heroku origin ``` -When we push to `origin`, we'll be pushing our project to GitHub. When we push -to `heroku`, we'll be pushing our project to Heroku. +Когда мы отправим изменения на удаленный репозиторий `origin`, они отправляться в соответствующий проект на GitHub. В случае с удаленным репозиторием `heroku`, следовательно, изменения отправятся в проект на Heroku. -Before we can do that, we'll have to set things up for Heroku to know what -kind of application we're building. We'll add a couple of "buildpacks" to set -things up: +Перед тем, как это делать, нам нужно будет настроить Heroku с целью указать, какое приложение мы создаем. Мы добавим пару «buildpacks», чтобы все подготовить: ```shell $ heroku buildpacks:add https://github.com/HashNuke/heroku-buildpack-elixir.git $ heroku buildpacks:add https://github.com/gjaldon/heroku-buildpack-phoenix-static.git ``` -Keep in mind that these commands won't make changes to our local files. If we -run the `git status` command, we'll see that nothing has changed. But we should -see the following output to let us know that our Heroku app is configured to -work with the Elixir code that we're going to send: +Имейте в виду, что эти команды не повлияют на локальные файлы. Таким образом, если выполнить команду `git status`, мы увидим, что ничего не изменилось. А вместо это будет отображен следующий вывод, сообщающий нам, что наше приложение настроено на Heroku для работы с Elixir-кодом, который мы собираемся отправить: ```shell $ heroku buildpacks:add https://github.com/HashNuke/heroku-buildpack-elixir.git @@ -193,9 +142,7 @@ Buildpack added. Next release on platform will use: Run git push heroku master to create a new release using these buildpacks. ``` -To set up the correct versions and settings we need for our application, create -a file called `elixir_buildpack.config` in the `platform` folder. Inside the -file, add the following contents: +Для установки правильных версий и настроек, которые потребуются для нашего приложения, создайте файл с именем `elixir_buildpack.config` в директории `platform`. Внутри файла добавьте следующее содержимое: ```config erlang_version=20.0 @@ -203,38 +150,30 @@ elixir_version=1.7.0 always_rebuild=true ``` -Since we're using the latest versions of Erlang, Elixir, and Phoenix, these -settings are necessary for the deployment to work. +Поскольку мы используем последние версии Erlang, Elixir и Phoenix, эти настройки необходимы для работы развертывания. -## Heroku Configuration +## Конфигурация Heroku -There are still a couple more steps we need to take to make sure our application -is ready to be pushed live to Heroku. Let's create a `Procfile` to tell -Heroku which command we want to run to start the Phoenix server. Create a file -called `Procfile` inside the `platform` folder, and add the following code: +Осталось сделать еще пару шагов, чтобы убедиться, что наше приложение готово к развертыванию на Heroku. Давайте создадим `Procfile` для указания Heroku, какую команду нужно запускать, чтобы запустить сервер Phoenix. Создайте файл с именем `Procfile` в директории `platform` и добавьте следующий код: ```Procfile web: MIX_ENV=prod mix phx.server ``` -Now we'll need to set some environment variables on Heroku. These are -configuration settings we'll need to get our app running. If we run the -`heroku config` command right now, we'll see that we don't currently have any -variables set up: +Теперь нам нужно установить некоторые переменные окружения на Heroku. Эти конфигурационные параметры нам понадобятся для запуска нашего приложения. Если мы выполним команду `heroku config` прямо сейчас, мы увидим, что в настоящее время у нас нет никаких установленных переменных: ```shell $ heroku config === platform Config Vars ``` -Since we're using PostgreSQL for our Phoenix application, we'll also want to -create a free Heroku add-on for our project with the following command: +Поскольку мы используем PostgreSQL для нашего приложения, нам нужно создать бесплатное дополнение Heroku для проекта с помощью команды ниже: ```shell $ heroku addons:create heroku-postgresql:hobby-dev ``` -This is what the output should look like: +Вот как должен выглядеть вывод: ```shell $ heroku addons:create heroku-postgresql:hobby-dev @@ -246,8 +185,7 @@ Created ... as DATABASE_URL Use heroku addons:docs heroku-postgresql to view documentation ``` -If we run `heroku config` again, we'll see that we now have a `DATABASE_URL` -variable configured (the actual URL has been removed in this example): +Если мы снова запустим `heroku config`, мы увидим, что переменная `DATABASE_URL` теперь определена (фактический URL был удален в этом примере): ```shell $ heroku config @@ -255,25 +193,20 @@ $ heroku config DATABASE_URL: postgres://... ``` -We'll also need to set a `SECRET_KEY_BASE` environment variable for production. -Phoenix can generate a secret key for us with the following command (note that -your key will be different from the example shown below): +Нам также потребуется установить переменную среды `SECRET_KEY_BASE` для продакшена. Phoenix может сгенерировать секретный ключ с помощью следующей команды (обратите внимание, что ваш ключ будет отличаться от приведенного ниже примера): ```shell $ mix phx.gen.secret ChVyb+s5O6qVKZabMCWwDPYHJbYqMpWppTZFZmsnULd+PDyXqQU36H8Rs6HXU0nl ``` -Then we can take that key and set it as the Heroku environment variable with -the following command (don't forget to replace the example key shown here with -the one you generated above): +Затем мы можем взять этот ключ и установить его как переменную окружения Heroku с помощью следующей команды (не забудьте заменить приведенный пример ключа на ваш, сгенерированный командной выше): ```shell $ heroku config:set SECRET_KEY_BASE="ChVyb+s5O6qVKZabMCWwDPYHJbYqMpWppTZFZmsnULd+PDyXqQU36H8Rs6HXU0nl" ``` -Now when we run the `heroku config` command we should be able to see the -settings for both the `DATABASE_URL` and the `SECRET_KEY_BASE`. +Теперь, если выполним команду `heroku config`, мы должны увидеть значения обеих переменных: `DATABASE_URL` и `SECRET_KEY_BASE`. ```shell $ heroku config @@ -282,11 +215,9 @@ DATABASE_URL: ... SECRET_KEY_BASE: ... ``` -## Production Deploy +## Развертывание на продакшен -Lastly, we need to make a few changes to the `prod.exs` file in the `config` -folder. Open that file and you'll see the following code along with a lot of -explanatory comments: +Наконец, нам нужно внести несколько изменений в файл `prod.exs` в директории `config`. Откройте этот файл, и вы увидите следующий код вместе с множеством пояснительных комментариев: ```elixir config :platform, PlatformWeb.Endpoint, @@ -295,8 +226,7 @@ config :platform, PlatformWeb.Endpoint, cache_static_manifest: "priv/static/cache_manifest.json" ``` -Let's make a couple of changes so it looks like this (replace -`YOUR-HEROKU-APP-NAME` with the app name you created on Heroku): +Давайте внесем пару изменений, чтобы код выглядел как показано ниже (замените `YOUR-HEROKU-APP-NAME` на имя приложения, которое вы создали в Heroku): ```elixir config :platform, PlatformWeb.Endpoint, @@ -307,9 +237,7 @@ config :platform, PlatformWeb.Endpoint, secret_key_base: Map.fetch!(System.get_env(), "SECRET_KEY_BASE") ``` -This allows us to set the `port`, the `host` name, and `secret_key_base`. We're -also configuring our app to use `https`. Right below that configuration code, -we also want to add a new block of code to configure our database: +Мы устанавливаем порт (`port`), имя хоста (`host`) и `secret_key_base`. Мы также настраиваем приложение на использования протокола `https`. Чуть ниже это кода с настройкой конфигурации, давайте добавим новый блок кода для настройки базы данных: ```elixir # Database configuration @@ -320,10 +248,7 @@ config :platform, Platform.Repo, ssl: true ``` -If you scroll down to the very bottom of the `prod.exs` file, you'll see a line -to import a secret configuration file. Since we're using environment variables -for Heroku, we won't need this. Let's comment that line out by placing a `#` -character at the beginning of the line: +Если прокрутить вниз до самого конца файла `prod.exs`, вы увидите строку для импорта секретного файла конфигурации. Поскольку мы используем переменные среды для Heroku, нам данная строчка не понадобится. Давайте закомментируем эту строчку, поместив символ `#` в самом начале: ```elixir # Finally import the config/prod.secret.exs @@ -331,24 +256,15 @@ character at the beginning of the line: # import_config "prod.secret.exs" ``` -You can also delete the `prod.secret.exs` file if you'd like since we won't -need it anymore. +Вы также можете удалить файл `prod.secret.exs`, если хотите, поскольку он больше не понадобиться. -## Static Asset Compilation +## Компиляция стических ресурсов -Phoenix uses [Webpack](https://webpack.js.org) to compile the static assets for -the front-end. We already added the Heroku buildpack for Phoenix static assets, -and now we just need to add configuration files to compile the assets as we -deploy our application to the production environment. +Phoenix использует [Webpack](https://webpack.js.org) для компиляции статических ресурсов фронтенда. Мы уже добавили buildpack Heroku для статических ресурсов Phoenix, и теперь нам всего лишь нужно добавить конфигурационные файлы для компиляции ресурсов при развертывании приложения в продакшене. -The buildpack we're using is highly configurable, and we can take a look at the -[configuration options](https://github.com/gjaldon/heroku-buildpack-phoenix-static#configuration) -available in the README. We're going to stick with the default options, but -we'll need to add a shell script file called `compile` (note that there's no -file extension and the file is simply named `compile`). +Используемый нами buildpack легко настраивается, и мы можем взглянуть на [конфигурационные опции](https://github.com/gjaldon/heroku-buildpack-phoenix-static#configuration), доступные в файле README. Мы собираемся придерживаться параметров по умолчанию, однако нужно добавить файл скрипта командной оболочки с именем `compile` (обратите внимание, что расширение файла отсутствует и файл просто называется `compile`). -Let's go ahead and create our `compile` file now at the root of our project and -add the following contents: +Давайте продолжим и создадим файл с компиляцией (`compile`) в корне проекта с таким содержимым: ```shell npm run deploy @@ -356,96 +272,69 @@ cd $phoenix_dir mix "${phoenix_ex}.digest" ``` -This allows our application to compile the front-end assets whenever we deploy -to Heroku. It runs the `"deploy"` script from the `package.json` file that's -located in the `assets` folder of our Phoenix project. That script runs the -`webpack --mode production` command for our front-end assets. Then, the -`compile` script changes back to the root Phoenix directory and runs the -`mix phx.digest` command to compress all our static files for the production -environment. +Этот набор команд компилирует внешние ресурсе всякий раз, когда мы развертываем приложение на Heroku. Сначала запускается npm-скрипт `"deploy"`, определенный в файле `package.json`, находящийся в директории `assets` проекта. Этот скрипт запускает команду `webpack --mode production` для сборки фронтенд-ресурсов. Затем скрипт `compile` возвращается в корневую директорию Phoenix и выполняет команду `mix phx.digest`, чтобы сжать все статические файлы. -## Deployment +## Развёртывание -Let's run our tests one more time to make sure we didn't break anything: +Давайте запустим тесты еще раз, чтобы проверить, что всё работает, как и раньше: ```shell $ mix test ``` -If everything is still passing, we'll commit our latest changes. If you ran -into any issues, check out the Phoenix docs for a similar set of steps for -[deploying an application to Heroku](https://hexdocs.pm/phoenix/heroku.html). +Если тесты по-прежнему успешно проходят, зафиксируем в системе контроля версий последние изменения. Если у вас возникли какие-либо проблемы, обратитесь к документации Phoenix за аналогичным набором шагов для [развертывания приложения в Heroku](https://hexdocs.pm/phoenix/heroku.html). ```shell $ git add . $ git commit -m "Update production configuration" ``` -We'll push the updates to GitHub first: +Для начала мы отправим обновления в репозитории на GitHub: ```shell $ git push origin master ``` -And now (the moment we've all been waiting for), we can push to Heroku: +А теперь (момент, которого мы все ждали!), мы можем отправить изменения на Heroku: ```shell $ git push heroku master ``` -We'll see _a lot_ of output when we deploy. If something goes wrong with the -deployment, it will let us know. Don't worry too much if you run into an issue -or two, because this process is admittedly tedious. The likelihood of -forgetting a comma or confusing the application names is high, but it's usually -just a matter of calmly working through any errors you come across. There are -Stack Overflow sections for both -[Heroku](https://stackoverflow.com/questions/tagged/heroku) -and [Phoenix](https://stackoverflow.com/questions/tagged/phoenix-framework) -that can be really useful if you run into issues. +Мы увидим _много_ результатов при развертывании. Если что-то пойдет не так, мы будем знать об этом. Не беспокойтесь слишком сильно, если вы столкнетесь с одной-двумя проблемами, потому что этот процесс, надо признать, утомителен. Вероятность того, что вы забудете запятую или запутаетесь с именами приложений, весьма высока, но обычно всё сводиться к спокойному решению ошибок, которые могут возникнуть. Есть разделы Stack Overflow для [Heroku](https://stackoverflow.com/questions/tagged/heroku) +и [Phoenix](https://stackoverflow.com/questions/tagged/phoenix-framework), которые могут оказаться очень полезными, если вы столкнетесь с проблемами. -It's worth the trouble once we get to see our app up and running live in -production! +Это стоит всех трудностей, как только мы увидим наше приложение работающим в продакшене! -## Up and Running +## Готово и работает -Once the deploy finishes, our app is finally up and running on Heroku! Inside -the `platform` folder, let's run the following from the command line to -see our application running on Heroku: +После завершения развертывания наше приложение наконец-то работает на Heroku! Внутри директории `platform` давайте запустим последнюю команду в этой главе, чтобы увидеть наше работающее приложение на Heroku: ```shell $ heroku open ``` -![Working Heroku Deploy](images/phoenix_testing_and_deployment/working_heroku_deploy.png) +![Работающее приложение на Heroku](images/phoenix_testing_and_deployment/working_heroku_deploy.png) -Our application is working in production! +Наше приложение теперь работает в продакшене! -## Running Migrations +## Выполнение миграций -Now that we managed to successfully get our application up and running on -Heroku, we can take one more step to automate our database migrations each time -we deploy to production. +Теперь, когда нам удалось успешно запустить приложение на Heroku, осталось сделать еще один шаг — автоматизировать выполнение миграций на базе данных при каждом развертывании в продакшен. -Open up the `Procfile` we created before, and add a new `release` line at the -top of the file: +Откройте ранее созданный файл `Procfile`, и добавьте новую строку с `release` в самый вверх: ```shell release: MIX_ENV=prod mix ecto.migrate web: MIX_ENV=prod mix phoenix.server ``` -This allows us to automate the database migrations before the Phoenix web -server starts in the production environment. And our app should now be fully -functional on Heroku with a working production database. +Теперь мы провели автоматизацию миграции базы данных до запуска веб-сервера Phoenix в продакшене. И наше приложение полностью функциональное на Heroku с работающей базой данных на продакшене. -![Working Production Players Index Page](images/phoenix_testing_and_deployment/working_players_page.png) +![Начальная страница игроков, работающая в продакшен-окружении](images/phoenix_testing_and_deployment/working_players_page.png) -## Summary +## Резюме -In this chapter, we were able to get all our Phoenix tests passing, push our -code to GitHub, and deploy our application successfully to Heroku! +В этой главе нам удалось добиться, чтобы все тесты Phoenix проходили, разместить код в репозитории на GitHub, а также успешно развернуть приложение на Heroku! -We're off to a solid start for our platform. Our back-end is up and running, -and we've picked up some introductory knowledge about Phoenix and Elixir. In -the next chapter, we'll learn more about Phoenix as we extend our player -features and allow new users to sign up. +Мы удачно начали работу над нашей платформой. Бэкенд настроен и работает, а мы приобрели ряд начальных знаний о Phoenix и Elixir. В следующей главе мы узнаем больше про Phoenix, расширив возможности наших игроков и позволим новым пользователям зарегистрироваться. From c686bf537d97f296a8e0f1804304822c1e71b9b5 Mon Sep 17 00:00:00 2001 From: Alexey Pyltsyn Date: Fri, 18 Jan 2019 12:33:41 +0300 Subject: [PATCH 08/10] appendix: initial translation --- manuscript/appendix.md | 124 ++++++++++++----------------------------- 1 file changed, 37 insertions(+), 87 deletions(-) diff --git a/manuscript/appendix.md b/manuscript/appendix.md index 0793e24..564d0a1 100644 --- a/manuscript/appendix.md +++ b/manuscript/appendix.md @@ -1,32 +1,22 @@ -# Appendix {#appendix} +# Приложение {#appendix} -## Quick Install +## Быстрая установка -This book is intended for developers with some previous experience, so -installing these languages and tools shouldn't be overly difficult or -time-consuming. Having said that, it's easy to get tripped up with installation -and configuration steps, so feel free to -[create a GitHub issue](https://github.com/elixir-elm-tutorial/elixir-elm-tutorial-book/issues) -if you think there's an easier approach to setting things up. +Эта книга предназначена для разработчиков, у которых есть некий предыдущий опыт разработки, поэтому установка перечисленных ниже языков и инструментов не должна быть слишком сложной или трудоемкой. При этом легко запутаться в действиях по установке и настройке, поэтому не стесняйтесь [открыть ишью в репозитории на GitHub](https://github.com/elixir-elm-tutorial/elixir-elm-tutorial-book/issues), если вы думаете, что есть более простой способ установки. -The intention for this chapter is to get everything we'll need installed -quickly so we can start creating Phoenix projects. +Цель этой главы — быстро установить всё, что нужно для того, чтобы мы могли приступить к созданию проектов на Phoenix. -These instructions assume that you're running macOS, but instructions can also -be found online for installing these tools on Linux. +В данных инструкциях предполагается, что используется macOS, но аналогичные инструкции по установке в системах на Linux можно найти в интернете. ### Elixir -First, let's install [Elixir](https://elixir-lang.org) with -[Homebrew](https://brew.sh). This command will also install the latest version -of [Erlang](https://www.erlang.org) as a dependency: +Сначала давайте установим [Elixir](https://elixir-lang.org) вместе с [Homebrew](https://brew.sh). Эта команда также установит последнюю версию [Erlang](https://www.erlang.org) в качестве зависимости: ```shell $ brew install elixir ``` -You can verify that Elixir has been installed properly by running the following -command: +Вы можете проверить правильность установки Elixir, если выполните следующую команду: ```shell $ elixir -v @@ -34,131 +24,91 @@ Erlang/OTP 20 Elixir 1.7.0 ``` -Any trouble with this step? Check out the -[Elixir install page](https://elixir-lang.org/install.html) or the -[Elixir section of Stack Overflow](https://stackoverflow.com/questions/tagged/elixir). +Есть проблемы с выполнением этого шага? Посетите [страницу установки Elixir](https://elixir-lang.org/install.html) или +[раздел, посвященный Elixir на Stack Overflow](https://stackoverflow.com/questions/tagged/elixir). ### Hex -[Hex](https://hex.pm) is the package manager for the Elixir and Erlang -ecosystems. Once you have Elixir installed, it's easy to install Hex with the -following command: +[Hex](https://hex.pm) — менеджер пакетов для экосистем Elixir и Erlang. После того, как вы установили Elixir, установить Hex легко с помощью данной команды: ```shell $ mix local.hex ``` -Any trouble with this step? Check out the -[Hex section of Stack Overflow](https://stackoverflow.com/questions/tagged/hex-pm). +Есть проблемы с выполнением этого шага? Изучите [раздел, посвященный Hex на Stack Overflow](https://stackoverflow.com/questions/tagged/hex-pm). ### Phoenix -[Phoenix](http://phoenixframework.org) is a web application framework built -with the Elixir language. You can install the latest version with the following -command: +[Phoenix](http://phoenixframework.org) — фреймворк для веб-приложений, созданный на языке Elixir. Вы можете установить последнюю версию с помощью следующей команды: ```shell $ mix archive.install https://github.com/phoenixframework/archives/raw/master/phx_new.ez ``` -You can verify that Phoenix has been installed properly by running the -`mix help` command, and you should be able to see a `mix phx.new` task that will -allow us to create new Phoenix applications. +Для проверки правильности установки Phoenix, выполните команду `mix help`, и вы сможете увидеть задачу `mix phx.new`, позволяющая создавать новые Phoenix-приложения. -Any trouble with this step? Check out the -[Phoenix installation docs](https://hexdocs.pm/phoenix/installation.html) or the -[Phoenix section of Stack Overflow](https://stackoverflow.com/questions/tagged/phoenix-framework). +Есть проблемы с выполнением этого шага? Посмотрите [документацию по установке Phoenix](https://hexdocs.pm/phoenix/installation.html) или +[раздел, посвященный Phoenix на Stack Overflow](https://stackoverflow.com/questions/tagged/phoenix-framework). ### PostgreSQL -We'll be using [PostgreSQL](https://www.postgresql.org) for our database. The -easiest way to get started if you're new to PostgreSQL is to use -[**Postgres.app**](https://postgresapp.com). It's a macOS application that -makes it really simple to get PostgreSQL up and running, and also creates a -`postgres` user that Phoenix uses as a default when creating databases. +Мы будем использовать [PostgreSQL](https://www.postgresql.org) в качестве нашей базы данных. Если вы новичок в PostgreSQL, проще всего начать с использования [**Postgres.app**](https://postgresapp.com). Это macOS-приложение, значительно упрощающее запуск и использование PostgreSQL, а также создает пользователя `postgres`, который Phoenix использует по умолчанию при создании баз данных. -Any trouble with this step? Check out the -[PostgreSQL detailed installation guides](https://wiki.postgresql.org/wiki/Detailed_installation_guides) -or the [PostgreSQL section of Stack Overflow](https://stackoverflow.com/questions/tagged/postgresql). +Есть проблемы с выполнением этого шага? Ознакомьтесь с [подробными руководствами по установке PostgreSQL](https://wiki.postgresql.org/wiki/Detailed_installation_guides) +или [с разделом PostgreSQL на Stack Overflow](https://stackoverflow.com/questions/tagged/postgresql). -## Working with Versions +## Работа с версиями -The steps above should be all that's required to get started. If you're -interested in working with multiple versions different languages, -check out the [asdf version manager](https://github.com/asdf-vm/asdf). +Описанных шагов должно быть достаточно для начала работы. Если вы заинтересованы в работе с несколькими версиями на разных языках, посмотрите на [менеджер версий asdf](https://github.com/asdf-vm/asdf). -## Recommended Tools +## Рекомендуемые инструменты -Throughout this book, we opt for a simple approach to afford ourselves an -opportunity to learn about Elixir, Phoenix, and Elm as we put together a demo -application. As you start to develop more involved projects, it's a good idea -to review additional tools and services that can make your life easier. +На протяжении всей этой книги мы выбираем простой подход, чтобы позволить себе возможность узнать об Elixir, Phoenix и Elm при создании демонстрационного приложения. Когда вы начнете разрабатывать более сложные проекты, рекомендуется изучить дополнительные инструменты и сервисы, которые помогут упростить жизнь. -The [hex.pm](https://hex.pm) package manager is an invaluable tool for finding -useful libraries for your projects. For example, if you want to allow your -users to write Markdown syntax, you can look up "Markdown" on hex.pm and find -that the [Earmark](https://github.com/pragdave/earmark) package works really -well for this. +Менеджер пакетов [hex.pm](https://hex.pm) — бесценный инструмент для поиска полезных библиотек для своих проектов. Например, если вы хотите дать возможность вашим пользователям использовать синтаксис Markdown, можно написать в поисковой строке «Markdown» на сайте hex.pm и увидеть пакет [Earmark](https://github.com/pragdave/earmark), который действительно хорошо подходит для этой задачи. -Listed below are additional tools for your consideration. +Ниже перечислены дополнительные инструменты на ваше рассмотрение. -### Authentication +### Аутентификация -Want to build more robust authentication features for your application? -Consider checking out the following options: +Хотите иметь более надежные возможности аутентификации для своего приложения? Попробуйте использовать следующие библиотеки: - [ueberauth](https://github.com/ueberauth/ueberauth) - [guardian](https://github.com/ueberauth/guardian) -### Authorization +### Авторизация -We briefly touched on authorizing actions in our demo application. If you need -to work with additional authorization policies, take the following into -consideration: +Мы кратко коснулись авторизационных действий в нашем демонстрационном приложении. Если вам нужно работать с дополнительными политиками авторизации, уделите внимание следующим сервисам: - [BodyGuard](https://github.com/schrockwell/bodyguard) -### Code Quality +### Качество кода -Credo is a code quality tool that performs static analysis on your Elixir code -and provides helpful tips and feedback. It's really helpful as a way to learn -solid Elixir conventions and keep the code throughout your project consistent. +Credo — инструмент контроля качества кода, выполняющий статический анализ кода Elixir и дает полезные советы и рекомендации. В реальности этот сервис полезен как способ изучения принятых соглашений в Elixir и поддержания единообразным кода во всем проекте. - [Credo](https://github.com/rrrene/credo) -### Documentation +### Документация -Elixir has amazing documentation tools, which explains why the docs are so -fantastic. Check out the Elixir guide on -[writing documentation](https://hexdocs.pm/elixir/writing-documentation.html) -and consider using `ExDoc` to generate docs for your project. +В Elixir есть замечательные инструменты документирования, объясняющие, почему документация такая классная. Ознакомьтесь с руководством Elixir по [написанию документации](https://hexdocs.pm/elixir/writing-documentation.html) и подумайте насчет использования `ExDoc`, чтобы создать документацию для вашего проекта. - [ExDoc](https://github.com/elixir-lang/ex_doc) ### Continuous Integration -Early versions of this book included material on Continuous Integration and -Continuous Delivery. Although it ended up being outside the scope of our -content, it's essential to have a CI server to automatically run your tests. -Check out the following options, and consider hooking them into your GitHub -repository to automatically deploy your application. +Ранние версии этой книги содержали информацию о непрерывной интеграции и непрерывной поставки. Несмотря на то, что данный материал выходит за рамки книги, важно иметь CI-сервер для автоматического запуска ваших тестов. Обратите внимание на следующие сервисы и рассмотрите возможность их подключения к вашему GitHub-репозиторию для автоматического развертывания приложения. - [CircleCI](https://circleci.com) - [Semaphore](https://semaphoreci.com) -### Monitoring +### Мониторинг -Once your project is deployed to production, it's a good idea to monitor the -performance and watch for errors. AppSignal is a good option for tracking this -data and keeping your application running smoothly. +После развертывания проекта в продакшен имеет смысл отслеживать производительность и наблюдать за ошибки. AppSignal в этом случае является хорошим вариантом для контроля за такими данными и обеспечением нормальной работы приложения. - [AppSignal](https://appsignal.com/elixir) -### Testing +### Тестирование -Because we used the Phoenix generators to scaffold out our initial features, -our demo application came with quite a few tests. So we have examples of how -to work with `ExUnit` in our project, but Wallaby is a great option for writing -highly readable integration tests concurrently. +Поскольку мы использовали генераторы Phoenix для разработки первых возможностей, наше демонстрационное приложение включает много тестов. Итак, у нас есть примеры того, как работать с `ExUnit` в нашем проекте, однако Wallaby — это отличный вариант для написания легко читаемых интеграционных тестов в многопоточном режиме. - [Wallaby](https://github.com/keathley/wallaby) From b7e443f1610f1035ae86346c07793181501b6dfb Mon Sep 17 00:00:00 2001 From: Alexey Pyltsyn Date: Fri, 18 Jan 2019 13:18:56 +0300 Subject: [PATCH 09/10] contact: initial translation --- manuscript/contact.md | 27 ++++++++++----------------- 1 file changed, 10 insertions(+), 17 deletions(-) diff --git a/manuscript/contact.md b/manuscript/contact.md index 6e47640..c1943d2 100644 --- a/manuscript/contact.md +++ b/manuscript/contact.md @@ -1,25 +1,18 @@ -# Contact +# Контакты -## Congrats +## Поздравления -Congrats on making it all the way to the end of the book. I'd _really_ love to -hear from you! +Поздравляю с окончанием чтения книги. Мне бы _очень_ хотелось получить от вас отзывы о книге! -We managed to accomplish our goal of building a fun project together and learn -a lot about functional web programming along the way. +Нам удалось достичь поставленной цели — вместе на протяжении книги создать интересный проект и узнать много нового о функциональном веб-программировании. -## Feedback +## Замечания и предложения -Were there additional concepts you'd like to have seen covered in the material? -Were there parts of the book that felt confusing? Was there something we could -have done differently in our approach? +Есть дополнительные концепции, о которых вы хотели бы прочитать в этой книге? Были ли какие-то части книги, которые вызывали путаницу? Что-то можно было сделать иначе? -If you have any feedback about the book's content or the demos contained -within, then feel free to reach out. +Если у вас есть какие-либо отзывы по содержанию книги или демонстрационному приложению, не стесняйтесь написать об этом. -One simple way to provide feedback is to email the author directly at -`bijanbwb@gmail.com`. Alternatively, feel free to create GitHub issues in -either the book's content repository or the demo repository: +Один из простейших способов поделиться своим мнением — написать автору по электронной почте `bijanbwb@gmail.com`. В качестве альтернативы, не стесняйтесь создавать ишью в соответствующих репозиториях на GitHub: -- [Book Content Issues](https://github.com/elixir-elm-tutorial/elixir-elm-tutorial-book/issues) -- [Platform Demo Issues](https://github.com/elixir-elm-tutorial/platform/issues) +- [Список ишью по содержанию книги](https://github.com/elixir-elm-tutorial/elixir-elm-tutorial-book/issues) +- [Список ишью по демонстрационному приложению платформы](https://github.com/elixir-elm-tutorial/platform/issues) From e32f8aef595c1d66b78adcfb094e42af17f519ed Mon Sep 17 00:00:00 2001 From: Alexey Pyltsyn Date: Sun, 20 Jan 2019 00:11:22 +0300 Subject: [PATCH 10/10] elm_introduction: initial translation --- manuscript/elm_introduction.md | 184 +++++++++------------------------ 1 file changed, 47 insertions(+), 137 deletions(-) diff --git a/manuscript/elm_introduction.md b/manuscript/elm_introduction.md index 38c8d1f..f40815e 100644 --- a/manuscript/elm_introduction.md +++ b/manuscript/elm_introduction.md @@ -1,31 +1,18 @@ -# Elm Introduction +# Знакомство с Elm -We're going to build the front-end of our application using the Elm language. -That's going to involve using data from our back-end Phoenix application, and -decoding it into an Elm front-end application. Then, we'll also use Elm to -start building minigames for our platform. But before we get into all that, -let's take a quick look about what Elm is, how it works, and why we're so -eager to use it. +Мы собираемся разработать фронтенд для нашего приложения, используя язык Elm. Для этого потребуется использовать данные из уже реализованного бэкенд-приложения на Phoenix и преобразовать их в фронтенд-приложение на Elm. Далее мы также будем использовать Elm для создания мини-игр для нашей платформы. Но прежде чем мы перейдем ко всему этому, давайте кратко рассмотрим, что такое Elm, как он работает и почему нам всё-же нужно его использовать. -## Introduction +## Введение -Elm is likely to look and feel a little foreign at first. But don't let that -scare you away, because it's a _very_ strong language that can be _very_ nice -to work with. +Поначалу Elm может выглядеть и казаться себя немного чужим. Но не позволяйте этому чувству спугнуть вас, потому что это _очень_ мощный язык, с которым _очень_ приятно работать. -The design of Elm allows the language to offer things that many other languages -simply can't. Not only does it enable developers to write code that is free -from errors, but also results in code that is easier to refactor and more -maintainable. +Дизайн Elm предлагает то, что многие другие языки просто не могут. Данный язык позволяет разработчикам писать код, не подверженный ошибкам, который легче рефакторить и поддерживать. -I could go on for months about how great Elm is (and I've done that at my local -Elm meetup), but let's dive into some basic examples. +Я мог бы месяцами рассказывать о том, какой хороший Elm (и я сделал это на локальном митапе по Elm), но давайте разберем несколько простых примеров. ## Hello.elm -We can start with a simple "Hello World" example as a demonstration of how easy -it can be to get Elm up and running. Here's what a simple Elm program (with a -filename of `Hello.elm`) looks like: +Мы можем начать с классического примера «Hello World», чтобы продемонстрировать, как легко начать работать с Elm. Вот как выглядит самая простая программа на Elm (с именем файла `Hello.elm`): ```elm module Hello exposing (main) @@ -37,73 +24,41 @@ main = Html.text "Hello World" ``` -The syntax is concise, and this serves as a quick way to display some text on a -page in the browser (we'll get to that in a second). But this is also a good -example in the sense that it shows a handful of things about Elm that might -seem unsettling at first. Where are all the parentheses and curly braces? -What's with the odd spacing? +Синтаксис лаконичен, позволяющий быстро отобразить текст на странице в браузере (мы вернемся к этому через секунду). Но это также хороший пример, поскольку показывает несколько особенностей Elm, которые на первый взгляд могут сбить с толку. Так, например, где все круглые и фигурные скобки? Что это за странный отступ? -## Elm Syntax +## Синтаксис Elm -The first line is Elm boilerplate for defining our module. Since this is a -functional language, everything we do is essentially going to be modules and -functions. Functions will be _everything_ to us, and modules will help us -gather and organize all those functions. What we're saying with the first line -of code is that we're creating the `Hello` module, and "exposing" the only -function (`main`) from it. So if someone wanted to use our application, they -would just need to import it and they could use whatever functionality we -provided in that `main` function. +Первая строка — это шаблонный код для определения модуля. Поскольку Elm это функциональный язык, то все, с чем мы работаем, представляет собой модули и функции. Функции будут служить для нас _всем_, когда как модули помогут нам собрать и организовать все эти функции. Итак, в первой строке кода мы создаем модуль `Hello` и «раскрываем» единственную функцию (`main`) в нем. Поэтому, если кто-то захочет использовать ваш модуль, ему нужно всего лишь импортировать его, и тогда он сможет использовать любую функциональность, предоставляемую данной функцией `main`. -## Modules, Functions, and Types +## Модули, функции и типы -Speaking of imports, the next line says `import Html`. This allows us to use -any function from Elm's built-in -[Html library](http://package.elm-lang.org/packages/elm-lang/html/latest/Html). +Кстати про импортирование — в следующей строке есть `import Html`. Эта строчка кода позволяет нам использовать любую функцию из встроенной [HTML-библиотеки](http://package.elm-lang.org/packages/elm-lang/html/latest/Html), поставляемой вместе с Elm. -The function that we're using in this program is the -[`Html.text`](http://package.elm-lang.org/packages/elm-lang/html/latest/Html#text) -function, which takes a single string as an argument. If we take a look at the -documentation for the `text` function, we can see the Elm type syntax: +Используемая функция в программе — это функция [`Html.text`](http://package.elm-lang.org/packages/elm-lang/html/latest/Html#text), которая принимает в качестве аргумента единственную строку. Если посмотреть на документацию к функции `text`, то можно увидеть синтаксис типа Elm: ```elm text : String -> Html msg ``` -That means when we added `Html.text "Hello World"` to our program, the -`"Hello World"` string was our only argument. And `Html msg` was the return -type. Don't worry too much about typing yet, but it's helpful to think about a -couple of quick things for now: +Это означает, что когда мы добавили строчку кода `Html.text "Hello World"`, строка `"Hello World"` является единственным аргументом. В то время как строка `Html msg` является возвращаемым типом. В данный момент пока еще беспокойтесь относительно типизации, однако полезно подумать над несколькими короткими вопросами: -- How many arguments does a function take? -- What is the type of each argument? -- What is the type of the return value? +- Сколько аргументов принимает функция? +- Какой тип у каждого аргумента? +- Какой тип возвращаемого значения? -In our case, `text` is the name of the function. Then, we use a `:` symbol -before the list of arguments. This function only takes a single argument, and -it's a `String`. Then, we use the arrow symbol `->` after the argument. Lastly, -we indicate the return type, which is an `Html msg`. The `msg` part isn't -important, and we could have said `Html a`. The important part is that we are -returning some HTML code that we are going to use to display the text on a page -in the browser. +В нашем случае `text` — это имя функции. Затем мы используем символ `:` перед списком аргументов. Эта функция принимает только один аргумент типа `String`. Далее мы используем символ стрелки `->` после аргумента. Наконец, мы указываем тип возвращаемого значения `Html msg`. Часть `msg` не важна, и вместо этого могло быть, например, `Html a`. Самое главное, что мы возвращаем некоторый HTML-код, который мы собираемся использовать для отображения текста на странице в браузере. -## Main Function +## Основная функция -The `main` function is the starting point for our application. When we run it, -the Elm runtime is going to look for `main`. But Elm is _way_ more fun to play -with than it is to read about, so let's finally run our example. +Функция `main` — отправная точка нашего приложения. Когда мы его запустим, среда выполнения кода Elm будет искать `main`. Но Elm _гораздо_ интереснее пробовать самому, чем читать про него, так что давайте наконец-то запустим пример. -Before we can run Elm code, we'll need to install Elm. There are different -ways of doing it, but the easiest way is to use `npm` since most web developers -have [Node.js](https://nodejs.org/en) installed already. Alternatively, there -are also installers available on the [Elm home page](http://elm-lang.org). +Прежде чем мы сможем выполним код Elm, нужно установить собственно сам Elm. Существуют разные способы, но самый простой — использовать `npm`, поскольку у многих веб-разработчиков уже установлен [Node.js](https://nodejs.org/en). Кроме того, на [главной странице Elm](http://elm-lang.org) есть также установщики. ```shell $ npm install -g elm ``` -That should be all you need. It globally installs the `elm` command on your -machine, so you can run it from the command line. In fact, type `elm` now and -take a look at the output (some output has been trimmed for readability): +Этого должно быть достаточно. Данная команда глобально установит утилиту командной строки `elm` на компьютер. По факту, если ввести сейчас `elm`, можно увидеть следующий вывод (некоторые данные были сокращены в целях удобства чтения): ```shell $ elm @@ -130,12 +85,7 @@ happy to help out. They hang out there because it is fun, so be kind to get the best results! ``` -We'll use several of these command line features eventually, but for now let's -focus on two of them. First, let's create a temporary directory called `elm` -that we'll use to hold our Elm files, and then we'll use the `elm init` command -we see above to fetch the libraries we need. Also note we don't necessarily -need to place this folder inside our existing Phoenix application yet, and that -we'll take care of integrating Phoenix and Elm in the next chapter. +В конечном итоге мы будем использовать некоторые из представленных выше возможностей командной строки, но пока давайте сосредоточимся на двух из них. Сначала создадим временную директорию `elm`, которую мы будем использовать для хранения наших Elm-файлов, а затем мы воспользуемся командой `elm init` для загрузки нужных библиотек. Также обратите внимание, что не обязательно помещать эту директорию в наше существующее приложение Phoenix, поскольку мы займемся интеграцией Phoenix и Elm в следующей главе. ```shell $ mkdir elm @@ -143,9 +93,7 @@ $ cd elm $ elm init ``` -We're creating an empty `elm` folder, and then when we run `elm init` it's -going to create all the `elm.json` we need (note again that this output has -been trimmed a bit for readability): +Мы создаем пустую директорию `elm`, а затем при выполнении `elm init` будет создан файл `elm.json` (обратите внимание, что снова вывод команды был немного обрезан для удобства чтения): ```shell $ elm init @@ -157,15 +105,10 @@ Would you like me to create an elm.json file now? [Y/n]: Y Okay, I created it. Now read that link! ``` -You might have noticed how friendly the Elm compiler is. The messaging has a -conversational tone that can help both beginners and experienced developers -alike. Feel free to check out the -[introductory documentation](https://elm-lang.org/0.19.0/init) mentioned in the -output for more information about setting up Elm projects. +Вы могли заметить, насколько дружелюбен компилятор Elm. Вывод имеет разговорный тон, который может помочь как начинающим, так и опытным разработчикам. Можете почитать [соответствующий раздел в документации](https://elm-lang.org/0.19.0/init), упомянутый в выводе, чтобы получить дополнительную информацию по настройке Elm-проектов. + +Сейчас у нас есть все, что нам нужно: файл `elm.json` для конфигурации проекта и папка `src` для хранения файлов с расширением `.elm`. Давайте создадим простой файл `Hello.elm` внутри директории `src` для нашей программы «Hello World»: -We have everything we need for now: an `elm.json` file for our project -configuration, and `src` folder to put our `.elm` files. Let's create the -simple `Hello.elm` file inside the `src` folder for our "Hello World" program: ```elm module Hello exposing (main) @@ -177,48 +120,34 @@ main = Html.text "Hello World" ``` -All that's left is to run our program. Elm comes with a utility called -`elm reactor` that we can use to serve our program locally and then access -it in our browser. Go ahead and run it from the command line: +Осталось только запустить программу. Вместе с Elm входит утилита `elm reactor`, которую мы можем использовать для локального запуска нашей программы и последующего доступа к ней в браузере. Идем дальше и выполняем из командной строки: ```shell $ elm reactor Go to to see your project dashboard. ``` -Now you can visit `http://localhost:8000` in your browser and see the files -and dependencies for our project. +Теперь можно посетить `http://localhost:8000` в браузере и увидеть файлы и зависимости проекта. ![elm reactor](images/elm_introduction/elm_reactor.png) -We only have a single Elm file (`Hello.elm`), so let's click the link in the -`src` folder to compile it and see the results. +У нас имеется только один Elm-файл (`Hello.elm`), поэтому давайте перейдем по ссылке в директорию `src`, чтобы скомпилировать его и посмотреть результаты. ![Elm Hello World Example](images/elm_introduction/elm_hello_world.png) ## elm-format -"Hello World" is admittedly not the most exciting example. But the good news is -that we have Elm installed and we have a simple program up and running. +Разумеется, «Hello World» — это не самый интересный пример. Однако уже хорошо, что уже установлен Elm, а также есть хоть простая, но рабочая программа. -Let's take a look a couple more things that will make our lives easier with -this example still in mind. +Давайте рассмотрим еще пару деталей, которые сделают нашу жизнь проще, имея в виду данный пример. -Before we move any further, definitely consider trying -[`elm-format`](https://github.com/avh4/elm-format). It's a plugin that you can -use with your editor that makes working with Elm much easier. It's particularly -great when you're getting started, because you can type a rough idea of what -you want to do and then immediately know if it's valid code as long as -`elm-format` reformats the code and doesn't mention errors or warnings. +Прежде чем двигаться дальше, обязательно стоит попробовать [`elm-format`](https://github.com/avh4/elm-format). Это плагин, который значительно облегчает работу с Elm, можно использовать вместе с вашим редактором. Это особенно актуально, когда вы только начинаете, потому что вы можете получить общее представление о том, что вы хотите сделать, а также сразу узнать, является ли написанный вами код корректным, пока `elm-format` переформатирует код без отображения ошибки или предупреждения. -While `elm-format` is not strictly necessary, and it's possible to write solid -Elm code without it, it's a remarkably helpful tool that can help you focus on -problem solving instead of worrying about valid syntax. +Хотя `elm-format` не является строго обязательным, и без него можно писать хороший код Elm, тем не менее это удивительно полезный инструмент, который поможет вам сосредоточиться на решении проблем, вместо того, чтобы думать о правильном синтаксисе. -## Comments and Type Signatures +## Комментарии и сигнатуры типов -Let's go ahead and add a quick comment with the `-- comment` syntax to -indicate the filename at the top: +Давай пойдем дальше и добавим сверху небольшой комментарий с помощью синтаксиса `-- comment`, который указывающий на имя файла: ```elm -- Hello.elm @@ -231,8 +160,7 @@ main = Html.text "Hello World" ``` -Next, let's refactor our `import` declaration slightly to be more explicit -about which functions we want to import from the `Html` module: +Далее, давайте немного улучшим объявление `import` для более четкого определения, какие функции мы хотим импортировать из модуля `Html`: ```elm -- Hello.elm @@ -245,7 +173,7 @@ main = text "Hello World" ``` -We can also add a type signature for our `main` function: +Мы также можем добавить сигнатуру типа для функции `main`: ```elm -- Hello.elm @@ -259,14 +187,9 @@ main = text "Hello World" ``` -When we create type signatures, we're restating the function name first. Then, -after the `:` character, we give the types of the arguments and the return -value. Since this function doesn't have any arguments, we're just giving the -return type here, which is `Html msg`. That just means we're returning some -HTML code when we return a value from the `Html.text` function that we're using. +При создании сигнатуры типов, мы сначала перезагружаем имя функции. Затем, после символа `:`, указываем типы аргументов и возвращаемое значение. Но так как у этой функции нет аргументов, мы просто указываем в данном случае тип возвращаемого значения, которым является `Html msg`. Это значение просто означает, что мы возвращаем некоторый HTML-код из используемой нами функции `Html.text`. -The pipe operator we discovered in Elixir also works in Elm. In fact, we can -rewrite our "Hello World" text in all uppercase letters with the following: +Оператор конвейера, который мы узнали в Elixir, также есть в Elm. Фактически, мы можем переписать текст «Hello World» прописными буквами следующим образом: ```elm -- Hello.elm @@ -282,23 +205,10 @@ main = |> text ``` -Inside the `main` function, we start with the raw `"Hello World"` string. Then, -we pipe that to the -[`toUpper`](http://package.elm-lang.org/packages/elm-lang/core/latest/String#toUpper) -function from the -[`String`](http://package.elm-lang.org/packages/elm-lang/core/latest/String) -module. Then, we pipe the result of that to the `text` function that will -return the `Html msg` that our function is meant to return. - -After seeing the results in the browser, feel free to delete the temporary -`elm` folder that we created in this chapter since we'll be setting things up -inside our Phoenix application in the next chapter. - -## Summary - -There's a lot more to Elm than what we've covered in our simple "Hello World" -example. But this is a good start to get a look at the syntax and see that it's -not so scary as it might seem at first. In the next sections, we're going to -set up our Phoenix application to use Elm for the front-end. We're also going -to talk about the Elm Architecture, and how to pull data from our API into the -front-end application. +Внутри функции `main` мы начинаем с простой строки `"Hello World"`. Затем передаем эту строку функции [`toUpper`](http://package.elm-lang.org/packages/elm-lang/core/latest/String#toUpper) из модуля [`String`](http://package.elm-lang.org/packages/elm-lang/core/latest/String). А потом передаем полученный результат в функцию `text`, возвращающее значение типа `Html msg`, которое определенное в нашей функции. + +После просмотра результатов в браузере, можете удалить временную директорию `elm`, которую мы создали в начале главы, поскольку мы приведем в порядок наше Phoenix-приложение в следующей главе. + +## Резюме + +Есть еще много чего в Elm, чем то, что мы рассмотрели в нашем примере «Hello World». Однако это хорошее начало, чтобы посмотреть на синтаксис и увидеть, что он не такой страшный, как может показаться на первый взгляд. В следующих разделах мы настроим наше Phoenix-приложение для использования с Elm, который будем использовать в качестве фронтенда. Мы также поговорим об архитектуре Elm и о том, как получать данные из API в фронтенд-приложение.