Mostrando entradas con la etiqueta Erlang. Mostrar todas las entradas
Mostrando entradas con la etiqueta Erlang. Mostrar todas las entradas

sábado, 30 de mayo de 2020

An Elixir Phoenix + Preact initial setup

It's been a long time since my last post 😅 Currently I'm starting to get my feet wet with Elixir (again, second attempt), because it is a functional language (I kinda love functional programming, although I'm no expert), and it is optimized for distributed and scalable applications. Also, they have a Web Framework called Phoenix, and I just found out that creating applications with socket connections seems to be a breeze with Phoenix Channels. So I've decided to build a small application, and also I'm taking the chance to give Preact (a ReactJS lightweight alternative) a try for the front-end.

TL;DR

Here is how I created my Elixir and Phoenix application, and set up Preact:

Prerequisites

For this project I already have installed, at the time of writing:
  • Erlang/OTP 22.2.7
  • Elixir 1.10.1
  • Phoenix 1.5.3
  • NodeJS 12.16.2
  • NPM 6.14.4

Create Phoenix web app

First, we are going to create a new Phoenix application. For the sake of simplicity, we are going to skip the creation of the Ecto repo for database access, as this will not affect the Preact set-up.


When asked, install all the required Elixir dependencies, so you don't have to do it later.

Set-up Preact

The Phoenix web application already includes Webpack, so we can proceed to install and setup Preact right away. To install Preact, we run the next command, inside the assets folder:


All the NPM commands should be run inside the assets folder, which contains the NPM package files.
Then, we need to alias React to Preact, so we can make use of any component from the vast React ecosystem, through Preact's compatibility layer. In order to do this, we need to point react
and react-dom imports to Preact, by adding the respective aliases to be resolved in our already present Webpack config file, which is assets/webpack.config.js, like so:



Set up JSX support

The next step is to be able to transpile JSX into plain Javascript. For this we need to add a babel plugin that will do this work, so we first proceed to install @babel/plugin-transform-react-jsx.


Then, we proceed to modify the assets/.babelrc file, to specify the function for JSX that should be used from the plugin:


We also need to modify the Webpack configuration to transpile the JSX files, by modifying the JS rule to also include and resolve JSX extensions:



Update routing

The last bit to finish the set-up is to update the route configuration provided by Phoenix, so the front-end routes can be managed by the Javascript router of our choice, to have a fully fledged single page app. The first step is to open the file lib/phoenix_preact_web/router.ex and move the scope block for "/" to the end, so all of the other routes can take precedence and be handled by Phoenix. Then, we modify the get section to always direct to the index action regardless of the path (lines 37-42):


This way, all routes that do not belong to the API, nor Phoenix dashboard, will load the index page.

Clean Phoenix page templates


Before start adding our UI components, we should get rid of all the static content that Phoenix added by default in our index page. So let's open the template file lib/phoenix_preact_web/templates/page/index.html.eex, and remove all its contents. Let's also open the layout template lib/phoenix_preact_web/templates/layout/app.html.eex and remove all of the body contents. The reason for all this cleanup is because we will use the index page's body to render our components, so we won't need all of that content to be rendered on the server side. The layout file will look something like this:



Render a component


Now that we have the skeleton set-up, we can proceed to add our first component. Let's create a components folder inside assets/js, and inside it add a folder named App, where we will place our initial component. We will end up with a folder structure like this:

Then create a file named index.jsx under our App folder, and add the following code to create a basic counter:


Finally, let's render the component in our main Javascript app file (assets/js/app.js):


Now we are ready to go! Let's run the web application in the command line with mix phx.server, and we will have something like this:


Notice that this is a very basic setup, so other ES6 features like class properties are not available and will require additional configurations.

The full project for this example is available at GitHub: https://github.com/guillegr123/phoenix_preact

Happy coding!

viernes, 23 de agosto de 2019

Aprendiendo un nuevo lenguaje: Erlang

Saludos. Ya tenía ratos de no escribir una entrada en el blog, jejeje. El motivo de esta entrada es, primeramente, para dar señales de vida. Y en segundo lugar, para compartirles un repositorio de ejercicios/ejemplos de código en Erlang.

¿Qué es Erlang?

Erlang es un lenguaje de programación usado para construir sistemas de software de tiempo real masivamente escalables, que requieren una alta disponibilidad, como: telecomunicaciones, banca, tiendas en línea, telefonía y mensajería instantánea.

¿Por qué Erlang?

La principal razón por la que he decidido aprender Erlang es porque es uno de los lenguajes utilizados por la empresa para la que trabajo como subcontratista. En segundo lugar, porque es un lenguaje que usa el paradigma de la programación funcional, el cuál me encanta desde que me lo enseñaron en la universidad con DrScheme (hoy Racket), el cual es una variante de LISP.

En tercer lugar es porque este lenguaje posee un runtime ya preparado para sistemas distribuidos, de alta concurrencia con tolerancia a fallos, e implementa out-of-the-box el modelo de actores, el cual me pareció muy interesante cuando lo aprendí con Scala y Akka en un curso de programación reactiva. De hecho Akka se basó en el modelo de actores implementado en Erlang.

En cuarto lugar que un día de estos, para una tarea que tenía asignada en el trabajo, necesitaba saber cómo funcionaba algo de la API del sistema. Actualmente me desempeño como desarrollador front-end, por lo que no toco nada de la API. Sin embargo, en esta ocasión antes de preguntar, me dió por curiosear el código fuente del backend, a ver qué tan lejos podía llegar, y debo decir que... no me sentí tan perdido como la chinita en el bosque de la China jajaja. Gracias a que los desarrolladores del backend tienen muy buenas prácticas para organizar el código y nombrar variables, fue posible intentar dilucidar qué hacían los pedazos de código que logré encontrar.

Por otra parte, yo ya había leído un poco de Erlang, y había empezado hace tiempo un curso en Elixir (que he dejado olvidado, por cierto), así que al menos sabía como se definían las funciones y se asignaban las variables. Además de esto, al ser un lenguaje funcional, tiene esa maravilla llamada pattern matching. Realmente no sé si es algo del paradigma funcional, pero todos los lenguajes funcionales que he tocado lo tienen, y en el código que alcancé a ver lo estaban usando, así que mas o menos pude imaginar la intención de las funciones.

Y en último lugar que unos compañeros del trabajo hablaron acerca de un sitio web para que los desarrolladores practiquen y prueben sus conocimientos, y decidí inscribirme. Al estar curioseando, vi que había una sección de prácticas de Programación Funcional, con ejercicios que se podían hacer en distintos lenguajes como Scala, Haskell, Clojure, Racket, Elixir y Erlang. Estoy más familiarizado con Scala, pero Racket no lo recuerdo mucho, Elixir ya se me borró del caché, Haskell solo conozco qué es, y con Clojure no he pasado del hola mundo. Pero como había visto Erlang recientemente, me llamó la atención, y me animé a hacer un par de ejercicios con él. Después de una gran perdida que me dí porque ya no me acordaba que las variables inician con mayúsculas y los símbolos con minúsculas (lo cuál no se apega a lo que estoy acostumbrado), logré completar uno de los ejercicios.

I can haz teh codez?


Para que no me vuelva a olvidar como hice algunas cosas por mi memoria de corto plazo, decidí agregar el ejercicio en un repositorio de GitHub, el cuál puede servir a futuro (cercano o lejano, aunque espero que no tan lejano) para ir compilando de cuando en cuando alguno que otro ejemplo o ejercicio interesante:


Cabe mencionar que soy un completo noob en Erlang, así que dudo que tenga buenas prácticas. Sin embargo, espero que a alguien que esté aprendiendo como yo le sirvan, y cualquier Pull Request con mejoras o más ejercicios es bienvenido.

Con la tecnología de Blogger.