<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Mario Cardoso on Medium]]></title>
        <description><![CDATA[Stories by Mario Cardoso on Medium]]></description>
        <link>https://medium.com/@mariorcardoso?source=rss-b3e0625479e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*C-eyyugRzFibBJ0qPhq09A.jpeg</url>
            <title>Stories by Mario Cardoso on Medium</title>
            <link>https://medium.com/@mariorcardoso?source=rss-b3e0625479e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 00:17:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mariorcardoso/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Browser screenshot tool with MediaStream API]]></title>
            <link>https://medium.com/onfido-tech/browser-screenshot-tool-with-mediastream-api-97ae79d23afe?source=rss-b3e0625479e------2</link>
            <guid isPermaLink="false">https://medium.com/p/97ae79d23afe</guid>
            <category><![CDATA[js]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[mediastream]]></category>
            <dc:creator><![CDATA[Mario Cardoso]]></dc:creator>
            <pubDate>Fri, 29 Apr 2022 14:20:10 GMT</pubDate>
            <atom:updated>2022-04-29T14:20:10.109Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XoIqIbCYu1gR-GNOlQpRqw.jpeg" /></figure><h3>Problem</h3><p>Recently we took on a challenge to create a solution for our Analysts who needed to perform a manual action as part of a traceability process. They needed to verify a user-submitted security code against a UK government database to prove a person’s right to work. Then, they needed to take a screenshot to keep a record of it. Considering our requirements we needed to control and automate the screenshot functionality in our application.</p><h3>Solution</h3><p><strong>Browser screenshot tool.</strong></p><p>The answer to the problem was to build a simple tool to take screenshots within the browser. But how? MediaStream API to the rescue!</p><p>What we did consisted of streaming one tab content to another tab video element and capturing one frame of the stream, turning it into an image, and sending the image to the server.</p><p>Let us first take a look at what the MediaStream API is and which parts we needed to build our solution.</p><h3>MediaStream API</h3><p>MediaStream API provides the interfaces and methods for working with streams and their tracks. It is related to <a href="https://developer.mozilla.org/en-US/docs/Web/API/WebRTC_API">WebRTC</a> which provides support for streaming audio and video data.</p><p>Of all the interfaces that make up the MediaStream API we used the MediaDevices and MediaStream interfaces.</p><h4>MediaDevices</h4><p>From MDN Web Docs:</p><blockquote><em>The MediaDevices interface provides access to connected media input devices like cameras and microphones, as well as screen sharing. In essence, it lets you obtain access to any hardware source of media data.</em></blockquote><p>The media input we are interested in the screenshot tool is the screen sharing one, so we can obtain its media content and get an image from it. This interface has several methods that we can call to prompt the user to select a display, portion of a display (such as a window or tab), or turn on the camera and/or microphone providing a MediaStream object containing the media data.</p><h4>MediaStream</h4><p>From MDN Web Docs:</p><blockquote><em>The MediaStream interface represents a stream of media content. A stream consists of several tracks, such as video or audio tracks. Each track is specified as an instance of </em><a href="https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamTrack"><em>MediaStreamTrack</em></a><em>.</em></blockquote><p>The MediaStream will contain the content of the stream, we will use it to feed the video element, get a frame, and convert it to the final image we want.</p><h3>Tool Example</h3><p>The simple sample tool we built has three main pieces, the react screenshot tool component and two main methods, one to set up the preview of the image and one to capture an image from the preview.</p><h4>ScreenshotTool</h4><p>The main component ScreenshotTool is fairly small, it has two buttons, one to start the image preview and one to capture the image in the preview element. To show the streaming content we have a video HTML element and to show the image captured we have an img element.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4fa919fc49fc697a56e10c0cc2e2a3a4/href">https://medium.com/media/4fa919fc49fc697a56e10c0cc2e2a3a4/href</a></iframe><h4>ImagePreview</h4><p>ImagePreview is one of the two main functions. It is called when the user clicks on the Preview button.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0296601fdd36e2dd7b172403285ab0c4/href">https://medium.com/media/0296601fdd36e2dd7b172403285ab0c4/href</a></iframe><p>It takes as an argument a reference to the video element that is used to set its source object with the MediaStream object that we get from calling the getDisplayMedia() and after selecting the tab or window we want to stream. By doing this the video HTML element starts to show the content of the stream, which in our case will be the content of one of the browser’s tabs.</p><h4>ImageCapture</h4><p>ImageCapture is the function responsible for taking the screenshot we want. In short, it takes a look at the stream content in the video HTML element, grabs a frame, and converts it to a png image.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3e859510810028115ef446dd257d352b/href">https://medium.com/media/3e859510810028115ef446dd257d352b/href</a></iframe><p>We use the getVideoTracks function to get the stream frame, and then we use the frame to generate a png image using a canvas element. Instead of using a canvas element, we tried to use the ImageCapture class and takePhoto function, but it didn’t work because we can’t take photos of muted tracks. For more details take a look <a href="https://github.com/w3c/mediacapture-screen-share/issues/141">here</a> and <a href="https://github.com/chromium/chromium/blob/master/third_party/blink/renderer/modules/imagecapture/image_capture.cc">here</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ced0a9e104141808632ab0cd592ccb6/href">https://medium.com/media/0ced0a9e104141808632ab0cd592ccb6/href</a></iframe><h4>Demo</h4><p><a href="https://screenshot-browser-demo.netlify.app/">Demo App</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FcAk7tBvjNEc%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DcAk7tBvjNEc&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FcAk7tBvjNEc%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/d988a103446b0b9ba2edf24e1afac199/href">https://medium.com/media/d988a103446b0b9ba2edf24e1afac199/href</a></iframe><h3>Conclusion</h3><p>We can use these amazing interfaces to easily build solutions to our problems that initially may sound a bit complicated but most of the complicated parts are very well implemented and documented. This article shows a very specific problem and solution but I think it is a good, simple, and creative example of what you can build with the MediaStream API.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97ae79d23afe" width="1" height="1" alt=""><hr><p><a href="https://medium.com/onfido-tech/browser-screenshot-tool-with-mediastream-api-97ae79d23afe">Browser screenshot tool with MediaStream API</a> was originally published in <a href="https://medium.com/onfido-tech">Onfido Product and Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Value Objects in Ruby on Rails]]></title>
            <link>https://medium.com/runtime-revolution/value-objects-in-ruby-on-rails-9df64bc8db34?source=rss-b3e0625479e------2</link>
            <guid isPermaLink="false">https://medium.com/p/9df64bc8db34</guid>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[value-objects]]></category>
            <dc:creator><![CDATA[Mario Cardoso]]></dc:creator>
            <pubDate>Thu, 29 Jun 2017 09:38:04 GMT</pubDate>
            <atom:updated>2017-06-29T12:45:56.071Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*luqPGefqe8_spk1vSncF8Q.jpeg" /></figure><p>Today I’m going to talk about value objects and how they can be used and identified in your Rails application.</p><p>The goal here is to have simple models and controllers by extracting some classes. Creating value objects is one way of achieving this. I would rather have a lot of small classes than have only a few big classes, since they are easier to test, change and understand.</p><p>I will explore some situations and give you some value object examples that should make your application simpler and easier to work with. These examples were taken from my own experience developing applications, and also several scenarios that I have come across in other great blog posts.</p><h3>What is a Value Object?</h3><p>As stated by <a href="https://martinfowler.com/eaaCatalog/valueObject.html">Martin Fowler a value object is</a>:</p><blockquote>A small simple object, like money or a date range, whose equality isn’t based on identity.</blockquote><p>A value object represents a simple entity whose equality is based on its value, meaning that two different objects are equal when they have the same value. Value objects should be immutable, so when two value objects are created equal they should remain equal. When we define a value object in Ruby we should define the == or &lt;=&gt; methods so we can compare them based in its value.</p><p>The primitive objects such as Symbol, String, Integer and Range defined in Ruby are the simplest examples.</p><h3>Why do we need them?</h3><p>Identifying value objects in your Rails application can significantly simplify your system. The advantages of refactoring your code and making use of value objects are:</p><ul><li>the separation of concerns</li><li>it allows you to combine behaviour with the data and add functionality to data without polluting the model</li><li>by isolating functionality your code is easier to test</li><li>removes duplication</li><li>improves the understanding and organisation of code. Operations on particular data are now gathered in a single place, instead of disperse throughout the code</li></ul><h3>How can we identify them?</h3><p>I usually consider four situations that are candidates for creating a value object:</p><ul><li>Arguments together all the time</li><li>One attribute with behaviour</li><li>Two inseparable attributes value and unit</li><li>Class enumerable</li></ul><h4>Arguments together all the time</h4><p>The first situation happens when we have two or more arguments that are passed and used together all the time, often known as a “Data Clump” (code smell). A date range is a common example, when start_date and end_date are passed together all the time in our methods. We can create a class DateRange with the attributes start_date and end_date and this class should be responsible for the start_date and end_date columns of a given ActiveRecord object and accommodate all the related behaviour. We could include methods like include_date?(date), include_date_range?(date_range), overlap_date_range?(date_range) and to_s. This class can look something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/36895bb4b3c1b803df5de84260763033/href">https://medium.com/media/36895bb4b3c1b803df5de84260763033/href</a></iframe><p>This is just a standard Ruby object that does not inherit from ActiveRecord::Base. This class can be used, for example, with an Event model with the following columns: name, description, address_city, address_state, starts_at, ends_at. The Event model could look something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0d17f0ae68c224b33c822dae52f42e27/href">https://medium.com/media/0d17f0ae68c224b33c822dae52f42e27/href</a></iframe><p>With all this in place, we get the following usage:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8dad00bd0a8be6b6e3d24a41db00b8ff/href">https://medium.com/media/8dad00bd0a8be6b6e3d24a41db00b8ff/href</a></iframe><p>Another simple scenario that is demonstrated in the book <em>The Rails 4 Way (3rd Edition), </em>is a Person model with a single Address, that can be modeled using composition like we did in the previous example. The Person class has the attributes name, address_city and address_state and looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/87498bb143af5b00eb1de4a4216dfd75/href">https://medium.com/media/87498bb143af5b00eb1de4a4216dfd75/href</a></iframe><p>The value object Address looks something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/78e2ddc0888ec07eb1d915c204b1d4dc/href">https://medium.com/media/78e2ddc0888ec07eb1d915c204b1d4dc/href</a></iframe><p>Again this is just a standard Ruby object. With all this in place we get a similar usage like we saw in the date_range example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d6d9d74e27e51178e66de92731211e7/href">https://medium.com/media/2d6d9d74e27e51178e66de92731211e7/href</a></iframe><p>As I mentioned previously, one of the advantages of extracting code that usually goes in the model and create value objects is that you can reuse them and here is an example of that since we could use the Address object in the Event model as well.</p><h4>One attribute with behaviour</h4><p>Another situation where a value object can be useful is when you have one simple attribute that needs some associated behaviour and such behaviour does not belong in the model. Imagine that you have a model Room that inherits from ActiveRecord::Base with a degrees attribute and then you add a Temperature class to answer some questions that your system may need related with the temperature value:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/01f3561ea02738d91c892f7e775590fa/href">https://medium.com/media/01f3561ea02738d91c892f7e775590fa/href</a></iframe><p>Besides the cold? and hot? methods we also defined the methods &lt;=&gt;, hash, and eql?<em> </em>which allow us to make use of operations like sort and uniq<em>. </em>We get the following usage:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5988436974c408fbe6fc350d5f7244fb/href">https://medium.com/media/5988436974c408fbe6fc350d5f7244fb/href</a></iframe><h4>Two inseparable attributes value and unit</h4><p>Another common situation is when you have value-unit pairs like temperature (degrees and unit), money (cents and currency), distance (value and unit), etc. A pair of this kind usually needs some conversions methods, from euros to dollars, from kelvin to fahrenheit, from miles to kilometres, etc. And not just conversions, but also math operations often require special handling. Since this is so common and involves some logic there are already a few gems that are basically value objects that you can include and start using them right away.</p><p>A very popular one is the <a href="https://github.com/RubyMoney/money">money gem</a>, which helps you deal with money and currency conventions by providing a Money class that encapsulates all information about a certain amount of money such as its currency and value. The gem readme file is very thorough and self-explanatory so if you are interested go ahead and take a look. You can use it in a model class like Product:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7885f79509884a949c1d3a0c2ea001e1/href">https://medium.com/media/7885f79509884a949c1d3a0c2ea001e1/href</a></iframe><p>In this case when asking for or setting the cost of a product, we would use a Money instance.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/98cdd36f9162e06b5a09f53c0dae4285/href">https://medium.com/media/98cdd36f9162e06b5a09f53c0dae4285/href</a></iframe><p>The use of this gem as a value object is also covered in the book The Rails 4 Way (3rd Edition). Money is one of the most complex value objects of this type, specially the part related with conversions, but you can find simpler examples like the <a href="https://github.com/shemerey/weight">weight value object</a>.</p><h4>Class enumerable</h4><p>It is common practice to define a value object in Rails models by creating an array class like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/358c5cf3e28f73841b63f83bb00138fa/href">https://medium.com/media/358c5cf3e28f73841b63f83bb00138fa/href</a></iframe><p>This practice is not good because the array values may be used in the model attributes but they have nothing to do directly with the model domain. Defining the value object like this has a few disadvantages like impossibility to add functionality to the value object without polluting the model and does not allow to reuse the object. So we can create an object to accommodate the data of that array and also add some useful methods if we need them. The value object class for the example above could look something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f65e100b082c5827bef8610981a79c70/href">https://medium.com/media/f65e100b082c5827bef8610981a79c70/href</a></iframe><p>We can get the set of possible sizes and have a method that can be used in select form fields. I think this is useful if you have more than one model that has the attribute size, if your model has a lot of those arrays and you want to slim your model or if you have logic associated with it. Another common example of this type is Color, when we need to have a set of colors that can be used in some persisted models.</p><h3><strong>Values</strong></h3><p>As they say in the <a href="https://github.com/tcrayford/Values/tree/master">github page</a>:</p><blockquote>Values is a tiny library for creating value objects in ruby.</blockquote><p>Values allows you to simplify your value objects definition by removing the need to write an initialiser, add a few handy methods like attribute accessors and forces your value object to be immutable.</p><p>Here is an example that I showed you before but now using the values gem:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6066efb217a74a77287262f16d245e10/href">https://medium.com/media/6066efb217a74a77287262f16d245e10/href</a></iframe><h3>Conclusion</h3><p>My goal here was to encourage you to extract some classes and make your models and controllers less bloated. I tried to do this by providing several value object examples and covering a variety of potential scenarios, which, I hope, will help identify when and how to use them in your own Rails applications.</p><h3>References</h3><p><a href="https://www.sitepoint.com/value-objects-explained-with-ruby/">https://www.sitepoint.com/value-objects-explained-with-ruby/</a><br><a href="https://martinfowler.com/bliki/ValueObject.html">https://martinfowler.com/bliki/ValueObject.html</a><br><a href="http://wiki.c2.com/?ValueObject">http://wiki.c2.com/?ValueObject</a><br><a href="http://blog.jasonharrelson.com/blog/2014/03/07/how-i-design-rails-applications-part-1-value-objects/">http://blog.jasonharrelson.com/blog/2014/03/07/how-i-design-rails-applications-part-1-value-objects/</a><br><a href="https://makandracards.com/alexander-m/43081-value-object">https://makandracards.com/alexander-m/43081-value-object</a></p><p><em>If you have any questions about this article let me know in the comments bellow.</em></p><p><em>I work at </em><a href="http://www.runtime-revolution.com/"><em>Runtime Revolution</em></a><em> from sunny Lisbon to everywhere. We transform ideas into scalable products. I’ve learned a lot with this amazing team while helping our clients build their products.</em></p><p><a href="http://www.runtime-revolution.com/">Runtime Revolution</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9df64bc8db34" width="1" height="1" alt=""><hr><p><a href="https://medium.com/runtime-revolution/value-objects-in-ruby-on-rails-9df64bc8db34">Value Objects in Ruby on Rails</a> was originally published in <a href="https://medium.com/runtime-revolution">Runtime Revolution</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Want to use ES6 with Rails right now ? Webpack to the rescue]]></title>
            <link>https://medium.com/runtime-revolution/want-to-use-es6-with-rails-right-now-webpack-to-the-rescue-ebefb2004e9e?source=rss-b3e0625479e------2</link>
            <guid isPermaLink="false">https://medium.com/p/ebefb2004e9e</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[webpack]]></category>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Mario Cardoso]]></dc:creator>
            <pubDate>Thu, 09 Mar 2017 12:01:52 GMT</pubDate>
            <atom:updated>2017-04-27T10:52:18.031Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VfLvBXBxcgd7-q_Tykup-g.jpeg" /></figure><p>Today I’m going to talk about setting up a Rails application so you can write complex JavaScript features using ECMAScript 6, also known as ECMAScript 2015, and its marvellous new features.</p><p>Nowadays we can do everything with JavaScript from the backend to the frontend, but for most of the challenges that I face daily as a Software Developer, I use Ruby on Rails since it’s a better fit for my needs, and also because I really enjoy building web applications using it. But when it comes to building more complex frontend features, JavaScript is the way to go, and that’s ok. JavaScript is a great programming language and over the past few years has improved immensely, particularly with the new ES6, and also with the arrival of new packaging and compilation tools, and also new frameworks and libraries.</p><p>Recently Rails 5.1.0.beta1 was released and I’m really happy with the new developments. Rails is embracing npm and Webpack, and as such we will be able to manage JavaScript dependencies with npm via Yarn and be able to compile JavaScript with Webpack with the new Webpacker gem.</p><p>Those new developments are still in beta and today most of us are still working in production applications that are still in Rails 4 (or less) and the upgrade might not be an option for now.</p><p>So in this article I will explore one way (of many) to configure a Rails application so we can write ES6 code, and include it in our applications without much effort.</p><h3>Problem</h3><p>While developing a Rails 4 application at some point I needed to incorporate some features that required a lot of JavaScript code. When I started the development of those features I soon felt the need to have classes and modules to better organize my code, so ES6 immediately came to my mind. Aside from those needs, writing code in ES6 felt more future proof since sooner or later Rails would embrace it (it should happen in 5.1.0).</p><p>Summing up my problem, I wanted to write ES6 code in a Rails 4 application, and maintain the normal behaviour of my asset pipeline without messing up with sprockets.</p><h3>Solution</h3><p>The solution I ended up with consisted in creating a separate folder called app-js in the rails project root directory that contains all the ES6 code and compiling it to browser compliant ES5 code that then would be place in the asset pipeline.</p><p>To get the ES6 code compiled and placed in the asset pipeline I used Webpack with Babel and I used npm to manage JS packages. In the end I got two configuration files package.json and webpack.config.js.</p><p>There are many more workarounds to get ES6 in Rails environment. Here I’ll explore one alternative that satisfied my needs.</p><p>The project directory ended up looking like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/170/1*zBXBnqE3sz5U8Yz5h0E9oA.png" /></figure><p>In the following sections I will explain this setup in more detail, while I walk you through the needed steps.</p><h3>Set up NodeJS and npm</h3><p>To get started we have to install a few tools. We need to install NodeJS and npm as we will use those to install and manage the packages we need for our app. Assuming you’re using brew, to install them on a mac you can do it with:</p><pre>brew install node</pre><p>That’s it! With Node and npm installed head over to the root directory where your Rails project lives and run the following command:</p><pre>npm init</pre><p>Go through all the steps by filling out the information you think is appropriate and in the end a package.json<strong> </strong>file will be generated. Don’t worry too much, you can always change it later. This file will allow you to manage the node modules your JS project depends on.</p><p>Now we need a compiler for our ES6 code. This is where Babel comes in. Babel is a JavaScript compiler that helps you write the latest version of JavaScript by compiling it to ES5 code, that today’s browsers can understand. We are going to install the babel-loader and babel-core packages that will be used to work with Webpack, as well as the ES2015 presets to load the code we will write.</p><pre>npm install --save-dev babel-loader<br>npm install --save-dev babel-core<br>npm install --save-dev babel-preset-es2015<br>npm install --save-dev babel-polyfill</pre><p>The sample app that I’m going to build to demonstrate this setup uses also <a href="https://konvajs.github.io/">konva.js</a>, a two dimensional canvas library. To be able to import it and use it in our code we have to install it:</p><pre>npm install konva --save</pre><p>From this point on you can install as many packages as you need. In this sample app we will only need konva. In the end of the process you should have a package.json file that looks something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e247f28848b20ad003425810f42c06e7/href">https://medium.com/media/e247f28848b20ad003425810f42c06e7/href</a></iframe><p>Since our first configuration file, package.json is finished, we will now create and configure the second configuration file we need, webpack.config.js.</p><h3>Set up Webpack</h3><p>Webpack is a module bundler that takes assets like JavaScript files with many dependencies and turns them into something that you can provide to a client web page. To do that, it uses loaders that are defined in a configuration file, to know how to compile the assets. In our case, we want to compile ES6 code to ES5 code compatible with the current browsers. We will do this by providing a JavaScript file as an entry point and then Webpack will analyse it and get all the dependencies used in our code, to generate a compiled file that we can include in the asset pipeline of the Rails project.</p><p>We have already installed all the packages we need in the previous step. The remaining task we have to perform is to create the Webpack configuration file itself. Go to the project root directory and create a new file named wepack.config.js defined as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/748ae4a01b5983ce643b0a4de68d2793/href">https://medium.com/media/748ae4a01b5983ce643b0a4de68d2793/href</a></iframe><p>We can identify three main areas in the configuration file, the entry point, output file and the module loaders.</p><p>We start by defining the path for the entry point. This is the main file in our JS application where all the subsequent dependencies will be loaded as they appear in the code. The output defines the name and path of the compiled file. After the compilation we will have only one file that can be added to the Rails asset pipeline and be treated like a normal JavaScript file. Finally we have the module loaders where we specify the JS project directory the babel-loader and the presets. In our case we have ES2015 as the only preset.</p><p>With Webpack configured you are ready to go. Now all you have to do to get your code compiled and in the assets pipeline is to run:</p><pre>webpack</pre><p>The output of that command should be something like this:</p><pre>Hash: a591cde9072bb3bd1422<br>Version: webpack 1.14.0<br>Time: 2721ms<br>    Asset    Size  Chunks             Chunk Names<br>app-js.js  877 kB       0  [emitted]  main<br>   [0] multi main 40 bytes {0} [built]<br>    + 305 hidden modules</pre><p>A file with all your JS code (in the app-js folder) will be generated and placed in the asset pipeline. One advantage of compiling your JS I found useful is that it automatically detects syntax errors, so you don’t have to load the JS and check the errors in the browser web page.</p><p>While developing your JS features, to avoid running Webpack every time you change something you can use the following command that will compile the code every time it detects any change:</p><pre>webpack --watch</pre><p>To get a better feeling on this, let’s take a look at a sample application where you can see this setup.</p><h3>Sample Application</h3><p>In the root app directory we will see four new things. We have two new folders, the app-js directory where we will put our JS code and the node-modules directory where the packages managed by npm will be placed. We have also the two configuration files, package.json and webpack.config.js.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/170/1*zBXBnqE3sz5U8Yz5h0E9oA.png" /></figure><p>Inside the app-js directory we can write an entire JS project that uses all the new ES6 features. It will be compiled into one file and placed in the asset pipeline. The code I have here is just one small example. I took inspiration in the <a href="https://konvajs.github.io/">konva.js</a> demo and created a few JavaScript classes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/164/1*kIhAbT5fH7PX0i4n3O_pBg.png" /></figure><p>The entry end point is the main.js file. This is the main file of our application where the code will start to execute. As you can see in this file we are using modules by importing classes that we depend on.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4aa559328becdc1da92360744bceca4f/href">https://medium.com/media/4aa559328becdc1da92360744bceca4f/href</a></iframe><p>Next we can see an example of two classes of this app where I use some ES6 features like classes and inheritance, modules, const and let.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/22a1033867d8bbaa1be56bd085fe6201/href">https://medium.com/media/22a1033867d8bbaa1be56bd085fe6201/href</a></iframe><p>If you need it, you can also create a folder name like ‘server-actions’ where you can define Ajax requests for controller actions. You can later bind these actions to some button in the interface so you can for example persist the data in the database.</p><p>This code is an example of what you can do with this configuration. I my case I wanted to use ES6 with classes and modules so I could build and grow my application in more structured way, since I was building a quite complex JS feature.</p><p>I also recommend that you add to gitignore the node-modules directory and the compiled file. Finally to get the file compiled in Heroku when you deploy it you need a post build instruction in the package.json configuration file to compile you JS assets and to do that your Heroku application setup should include the <a href="https://elements.heroku.com/buildpacks/heroku/heroku-buildpack-nodejs">NodeJS builpack</a>.</p><h3>Conclusion</h3><p>Webpack, npm and ES6 are here to stay, and so is Rails. The JavaScript ecosystem always brings us something new, which is great, it means the community is working really hard to develop great tools that help us build better web applications. But sometimes I feel a bit lost on what tools I should use, since we have so many, and new ones are arriving all the time. On the other hand, Ruby on Rails is already 11 years old and is now a mature framework and when things settle down a bit in the JS world they eventually come to the Rails framework. Rails 5.1.0 is the proof of that, since it will include Yarn and Webpack.</p><p>In the meanwhile even though Rails 5.1.0 is in beta you can still write ES6 and include it in your application. All you need is two small configuration files like the ones I mentioned. Later when Rails 5.1.0 is released, and your app is ready for the upgrade, you can reuse all the code you wrote. I’m really happy with the new developments in Rails and looking forward to see what the developers and the community will do with them.</p><p>The code for the sample app can be found here: <a href="https://github.com/mariorcardoso/rails_webpack_npm_es6">https://github.com/mariorcardoso/rails_webpack_npm_es6</a><br>You can see the app live in Heroku here: <a href="https://rails-webpack-npm-es6.herokuapp.com/">https://rails-webpack-npm-es6.herokuapp.com/</a></p><p><em>Did you have any comments or feedback about this article? If so let me know in the comments bellow.</em></p><p><em>I work at </em><a href="http://www.runtime-revolution.com/"><em>Runtime Revolution</em></a><em> from the sunny Lisbon to everywhere. We transform ideas into scalable products. I’ve learned a lot with this amazing team while helping our clients build their products.</em></p><p><a href="http://www.runtime-revolution.com/">Runtime Revolution</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ebefb2004e9e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/runtime-revolution/want-to-use-es6-with-rails-right-now-webpack-to-the-rescue-ebefb2004e9e">Want to use ES6 with Rails right now ? Webpack to the rescue</a> was originally published in <a href="https://medium.com/runtime-revolution">Runtime Revolution</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>