<?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 ManasTech on Medium]]></title>
        <description><![CDATA[Stories by ManasTech on Medium]]></description>
        <link>https://medium.com/@manastech?source=rss-e2d636f010c9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*pZdjHiwvggLBSS20.png</url>
            <title>Stories by ManasTech on Medium</title>
            <link>https://medium.com/@manastech?source=rss-e2d636f010c9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 19:11:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@manastech/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[From a DB to JSON with Crystal]]></title>
            <link>https://medium.com/@manastech/from-a-db-to-json-with-crystal-df1749a5fe4a?source=rss-e2d636f010c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/df1749a5fe4a</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[json]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[crystal-lang]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[ManasTech]]></dc:creator>
            <pubDate>Mon, 16 Jan 2017 00:00:00 GMT</pubDate>
            <atom:updated>2017-01-16T16:18:37.965Z</atom:updated>
            <content:encoded><![CDATA[<p>In this post we will cover how to stream data from a database via HTTP in JSON format. Crystal allows us to build an implementation that does not stress the resources as much, by avoiding unnecessary memory allocations of intermediate object when possible. This can be accomplished thanks to the APIs of these modules: <a href="https://crystal-lang.org/api/latest/JSON.html">JSON</a>, <a href="https://crystal-lang.org/api/latest/HTTP/Server/Response.html">Http::Server::Response</a> and <a href="http://crystal-lang.github.io/crystal-db/api/latest/">DB</a>.</p><p>Our goal is to build two HTTP endpoints:</p><ol><li>GET / that will list all the tables in the DB</li><li>GET /:table_name that will respond with the table content as JSON (<a href="http://ndjson.org/">NDJSON</a> actually)</li></ol><p>We will use <a href="http://kemalcr.com/">Kemal</a> to avoid dealing with routing manually.</p><h3>The skeleton</h3><p>The following steps will render a basic skeleton of the app consisting of two empty endpoints and a database access point:</p><ol><li>specify the database_url,</li><li>open a <a href="https://crystal-lang.org/docs/database/connection_pool.html">connection pool</a>,</li><li>setup Kemal routing handlers,</li><li>start Kemal server.</li></ol><pre>require &quot;kemal&quot;<br><br>database_url = &quot;sqlite3://....&quot;<br>db = DB.open database_url<br><br>get &quot;/&quot; do |end|<br>  # ...<br>End<br><br>get &quot;/:table_name&quot; do |env|<br>  # ...<br>end<br><br>Kemal.run<br>db.close</pre><p>For convenience we’ll now focus on SQLite, but we’ll extend the solution to other drivers at the end of the article. Now is good time to check that your shard.yml has at least:</p><pre>dependencies:<br>  kemal:<br>    github: kemalcr/kemal<br><br>  sqlite3:<br>    github: crystal-lang/crystal-sqlite3</pre><p>Note: You can grab a quick sample database from <a href="http://www.sqlitetutorial.net/sqlite-sample-database/">chinook</a>.</p><h3>Get the tables</h3><p>Let’s assume that a method table_names(db) will return the names of the tables as an array of String, then a JSON encoded result could be programmed as follows:</p><pre>get &quot;/&quot; do |env|<br>  env.response.content_type = &quot;application/json&quot;<br>  table_names(db).to_json<br>end<br><br>def table_names(db)<br>   # return an array of strings<br>end</pre><p>Usually a database does not have a huge amount of tables. So, holding an array of <em>all</em> the tables names does not sound too heavy. The #to_json method will create a string with the JSON representation and send it to the client. We will cover more advanced techniques to generate JSON later in this post.</p><p>We can get the table names from SQLite with:</p><pre>def table_names(db)<br>  sql = &quot;SELECT name FROM sqlite_master WHERE type=&#39;table&#39;;&quot;<br>  db.query_all(sql, as: String)<br>end</pre><p>#query_all returns an array with all the rows of the query result. Friendly reminder: use it with caution because the array of all the returned rows could be <em>quite</em> large.</p><h3>Get the rows</h3><p>Let’s assume that a method write_ndjson(io, col_names, rs) will write an NDJSON entry for the current row in the io with the specified column names. We could program a response of the whole table as follows:</p><pre>get &quot;/:table_name&quot; do |env|<br>  env.response.content_type = &quot;application/x-ndjson&quot;<br>  table_name = env.params.url[&quot;table_name&quot;]<br>  unless table_names(db).includes?(table_name)<br>    # ignore if the requested table does not exist.<br>    env.response.status_code = 404<br>  else<br>    db.query &quot;select * from #{table_name}&quot; do |rs|<br>      col_names = rs.column_names<br>      rs.each do<br>        write_ndjson(env.response.output, col_names, rs)<br>      end<br>    end<br>  end<br>end<br><br>def write_ndjson(io, col_names, rs)<br>  # ...<br>end</pre><p>Before jumping into the details of how we could code write_ndjson let’s analyze the HTTP response.</p><p>Usually the server will build the dynamic response in a memory buffer before sending it, placing headers before the actual content starts, such as the Content-Length information. This is how the listing of the table names works, and you can see that for yourself with a $ curl -v <a href="http://0.0.0.0:3000.">http://0.0.0.0:3000.</a></p><p>In this case, since each row is a self contained json, we could stream one row at a time and this will minimize the memory usage on the server side. The client will be able to process the data as it comes. This mechanism is called <a href="https://en.wikipedia.org/wiki/Chunked_transfer_encoding">chunked response</a> if you want to go into the details.</p><p>To allow the response to be streamed we need to flush the output buffer right after each row is encoded as json.</p><pre># ...<br>    rs.each do<br>      write_ndjson(env.response.output, col_names, rs)<br>      # force chunked response<br>      env.response.output.flush<br>    end<br># ...</pre><p>The next step is how to weave the data coming from the DB to the response IO without creating many intermediate structures. In some DB libraries the approach is to get an array or hash of the full row. Crystal-db is designed to provide access as straightforward and as fast as possible, without intermediaries or multiples objects. The data is already waiting to be read in the database connection. It has certain fixed order if the connection is via a socket (like in MySQL or PostgreSQL), but this is not a problem since we are building a JSON object.</p><pre>def write_ndjson(io, col_names, rs)<br>  JSON.build(io) do |json|<br>    json.object do<br>      col_names.each do |col|<br>        json_encode_field json, col, rs.read<br>      end<br>    end<br>  end<br>  io &lt;&lt; &quot;\n&quot;<br>end</pre><p>With JSON.build we start a <a href="https://crystal-lang.org/api/0.20.4/JSON/Builder.html">JSON::Builder</a> that will provide convenient methods to emit a JSON straight into the IO.</p><p>The database can return values of many types. Most of them can be encoded directly into JSON: String, Ints, etc. But some of them can’t, like Slice(UInt8) (aka Bytes). So json_encode_field(json, col, value) is used to encode the value in an efficient way.</p><pre>def json_encode_field(json, col, value)<br>  case value<br>  when Bytes<br>    # custom json encoding. Avoid extra allocations.<br>    json.field col do<br>      json.array do<br>        value.each do |e|<br>          json.scalar e<br>        end<br>      end<br>    end<br>  else<br>    # encode the value as their built in json format.<br>    json.field col do<br>      value.to_json(json)<br>    end<br>  end<br>end</pre><p>Note that this method streams a json array directly from Bytes, yet there is no actual Array in memory. The Bytes could be a huge BLOB so it would be desirable to avoid creating a temporal object just to encode it as JSON. The data is already in memory, let’s just use it.</p><h3>Closing up</h3><p>It’s fascinating how many concepts can fit in less than 50 lines of code.</p><p>Don’t forget to check the <a href="https://github.com/bcardiff/sample-crystal-db_json">full source code</a> which can be used with any of the crystal-db supported drivers: MySQL, PostgreSQL or SQLite!</p><p><em>Originally published at </em><a href="https://manas.tech/blog/2017/01/16/from-a-db-to-json-with-crystal.html"><em>manas.tech</em></a><em> on January 16, 2017.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df1749a5fe4a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Static is Back]]></title>
            <link>https://medium.com/@manastech/static-is-back-73c00179973d?source=rss-e2d636f010c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/73c00179973d</guid>
            <category><![CDATA[agile]]></category>
            <category><![CDATA[scrum]]></category>
            <dc:creator><![CDATA[ManasTech]]></dc:creator>
            <pubDate>Tue, 15 Nov 2016 00:00:00 GMT</pubDate>
            <atom:updated>2017-01-06T17:25:09.523Z</atom:updated>
            <content:encoded><![CDATA[<p>Having been in the field of software development for over 11 years, which is not much but should be enough to <a href="http://www.wisdomgroup.com/blog/10000-hours-of-practice/">start gathering some understanding</a> of the field, I’ve had the chance to see different trends come and go.</p><h3>Agile and back again</h3><p>The Agile Manifesto from 2001 started a document-free revolution in software development, which stuck until just a few years ago. It was a huge change, as it offered a way out of the heavily <em>enterprisey</em> world that forced you to spend hours behind documents that could have been totally skipped. From <a href="https://www.pandastrike.com/posts/20150304-agile">“Flaws in Scrum and Agile”</a>, emphasis mine:</p><blockquote>When the Agile Manifesto was written, waterfall development was king. Agile deposed waterfall from its status as the dominant software development paradigm. Waterfall revolved around writing tedious documents, and face-to-face conversation was indeed superior to that. In 2001, Subversion was still new, Git did not exist, Skype didn’t exist either, and the closest contemporary equivalent to GitHub was SourceForge. “Face-to-face conversation,” in the Agile Manifesto, was “the most efficient and effective method of conveying information” because the other methods were terrible.</blockquote><blockquote>But when you’re reviewing a pull request, a GitHub diff usually beats face-to-face conversation. And this is not a fluke. Remote work requires a ton of writing, and that’s one of the best things about it. […] <strong>Waterfall used too much written communication, but Agile doesn’t use enough.</strong></blockquote><p>I won’t reproduce here the entirety of the article, or the many more that come up as soon as you Google for <a href="http://lmgtfy.com/?q=agile+is+dead">Agile is Dead</a>, but you get the idea. Having a written support to be able to work offline, where you can settle down your thoughts, and where you can return months later to find out what the heck were you thinking when you decided to implement <em>that</em>, is invaluable.</p><p>Whether the successor to Agile is <a href="https://www.pandastrike.com/posts/20150304-agile">Remote</a>, <a href="https://gradle.org/blog/agile-is-dead/">Continuous Delivery</a> or <a href="https://www.linkedin.com/pulse/agile-dead-matthew-kern">Devops</a> (<a href="https://pragdave.me/blog/2014/03/04/time-to-kill-agile/">or we just rethink it</a>), the point I’m trying to make here is that the brilliant (no irony here) folks behind the Agile Manifesto did not want to eradicate Comprehensive Documentation by burying it with Working Software. They wanted to make a break from the suffocating world that Waterfall and other document-heavy processes had become.</p><h3>Back to programming</h3><p>This endless introduction brings me to the subject matter of this article: the same is happening in the field of programming languages.</p><p>After nearly a decade of having Java-like type systems get in the way of <em>actually</em> getting things done, and having to deal with <a href="https://www.quora.com/What-are-the-most-ridiculous-Java-class-names-from-real-code">AbstractSingletonProxyFactoryBeans</a>, we as programmers welcomed dynamic languages as a breeze of fresh air. Personally, I remember working on my first Ruby and Python programs after years of C# and Java, and become amazed at the increase in productivity, as well as the true happiness that came from coding in them. Things were now <a href="https://xkcd.com/353/">simple</a> (or should I say <a href="https://www.infoq.com/presentations/Simple-Made-Easy">easy</a>?) as they should have always been.</p><p>We no longer had to work bounded by the crutches of an overly zealous type system, and could finally be free to code at will.</p><p>Fast forward quite a few years, to the point where we have massive codebases written in Ruby and Python, and we are starting to have second thoughts. We are now seeing a backlash, where the mainstream dynamic programming languages are having or considering additions to ensure type safety. From <a href="http://www.ybrikman.com/writing/2015/02/06/are-static-typing-and-functional/">Are static typing and functional programming winning?</a>, though I want to focus on static only:</p><p><em>Some of the most popular dynamic languages are considering some form of static typing:</em></p><ol><li><strong><em>Ruby</em></strong><em>: Matz announced that </em><a href="https://www.omniref.com/blog/blog/2014/11/17/matz-at-rubyconf-2014-will-ruby-3-dot-0-be-statically-typed/"><em>Ruby 3.0 may have type annotations</em></a><em>.</em></li><li><strong><em>Python</em></strong><em>: Guido van Rossum sent out a </em><a href="http://www.infoq.com/news/2014/08/python-type-annotation-proposal"><em>proposal to add type annotations to Python</em></a><em>.</em></li><li><strong><em>PHP</em></strong><em>: Facebook has released </em><a href="http://hacklang.org/"><em>Hack</em></a><em>, which supports type annotations on top of the PHP syntax. Moreover, PHP itself already has </em><a href="http://php.net/manual/en/language.oop5.typehinting.php"><em>Type Hinting</em></a><em> and may add </em><a href="https://wiki.php.net/rfc/return_types"><em>return type declarations</em></a><em>.</em></li><li><strong><em>JavaScript</em></strong><em>: Facebook has released </em><a href="http://flowtype.org/"><em>Flow</em></a><em>, Microsoft has released </em><a href="http://www.typescriptlang.org/"><em>TypeScript</em></a><em>, Google has released </em><a href="https://www.dartlang.org/"><em>Dart</em></a><em> and </em><a href="https://docs.google.com/document/d/11YUzC-1d0V1-Q3V0fQ7KSit97HnZoKVygDxpWzEYW0U/edit"><em>AtScript</em></a><em>, and there are many statically typed languages that compile to JavaScript, including </em><a href="http://www.gwtproject.org/"><em>GWT</em></a><em> (Java to JavaScript), </em><a href="http://www.scala-js.org/"><em>Scala.js</em></a><em> (Scala to JavaScript), </em><a href="http://haste-lang.org/"><em>Haste</em></a><em> (Haskell to JavaScript), and </em><a href="https://github.com/purescript/purescript"><em>purescript</em></a><em> (Haskell-ish to JavaScript).</em></li></ol><p>Again, if you <a href="http://lmgtfy.com/?q=static+typing">Google for static typing</a>, you will find a large number of articles stating its benefits in terms of performance, tooling, refactoring, mistake prevention, and even in the fact that they actually <em>help you</em> while coding by reducing the cognitive load of requiring the programmer to keep in his/her head which-type-is-going-where. I particularly recommend <a href="https://medium.com/techboi/on-tooling-and-static-typing-12bfa8f5db00#.qdg8i3u3z">this recent article</a>, especially because it ends with a great list of <em>other</em> articles on the subject. Unsurprisingly, if you look for <em>older</em> articles on static typing, when the feeling about it was quite different, you might stumble upon slightly opinionated gems such as <a href="https://www.jayway.com/2010/04/14/static-typing-is-the-root-of-all-evil/">this one</a>.</p><p>And again, we did not jump into dynamic languages because we thought that types were the root of all evil (well, maybe some folks did), we jumped because we needed a clean break from the bureaucratic nightmare that had surrounded Enterprise-Edition languages. And just as with document-oriented methodologies, after we have spent enough time away from them, we begin to recognise their good parts once again, and bring them into our worklife in a saner way.</p><h3>Where we stand</h3><p>Seeing this re-valuation of statically-typed languages in the very recent years, I can’t help but think that at Manas the correct decisions were made when we1<a href="https://manas.tech/blog/2016/04/01/the-story-behind-crystal.html">started developing a new language</a>, choosing to bring together the syntax and friendliness of Ruby, with static types powered by global type inference. This yields a programming environment where types <em>do</em> provide useful help and information, yet they do not clutter the code and get in the way.</p><p>After going through the two mentioned opposing tendencies in programming languages, <a href="http://crystal-lang.org/">Crystal</a> truly feels like the natural next-step in this chain. Having a static type system that is helpful yet not overwhelming requires a very delicate balance, one that we have managed to attain only after years of being on both sides of the fence.</p><p><em>Originally published at </em><a href="https://manas.tech/blog/2016/11/15/static-is-back.html"><em>manas.tech</em></a><em> on November 15, 2016.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73c00179973d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Running Crystal on Docker]]></title>
            <link>https://medium.com/@manastech/running-crystal-on-docker-d001196f1265?source=rss-e2d636f010c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/d001196f1265</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[crystals]]></category>
            <category><![CDATA[crystal-lang]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[ManasTech]]></dc:creator>
            <pubDate>Wed, 28 Sep 2016 00:00:00 GMT</pubDate>
            <atom:updated>2017-01-06T17:29:01.281Z</atom:updated>
            <content:encoded><![CDATA[<p>We have been migrating most of our projects to run on <a href="https://www.docker.com/">Docker</a> containers <a href="https://manas.tech/blog/2015/12/15/logging-for-rails-apps-in-docker.html">for a while</a> now, and since Crystal is our new favourite language ever since <a href="https://manas.tech/blog/2016/04/01/the-story-behind-crystal.html">its first commit</a>, running Crystal on Docker was a natural consequence as soon as we started using it in production.</p><p>The Crystal team at Manas keeps a debian-based image in <a href="https://hub.docker.com/r/crystallang/crystal/">Docker Hub</a> for every new release of the language, and extending from the image is incredibly easy. Assuming your project has a shards.yml file, <a href="https://crystal-lang.org/docs/using_the_compiler/index.html#creating-a-project-or-library">as every Crystal project should</a>, creating an image for your project is as easy as the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eaea56c1b86b351dce55519b5009fffa/href">https://medium.com/media/eaea56c1b86b351dce55519b5009fffa/href</a></iframe><p>Similar as you would <a href="https://docs.docker.com/compose/rails/">do in a Ruby app</a>, we first add the definition of the dependencies (i.e. the shard files) and install them, so any subsequent changes on the app itself that do not impact on the dependencies can reuse the Docker build cache. The next and final step is to compile the project <strong>in release mode</strong>, and set it as the default command for the image.</p><p>As a base .dockerignore file you could use:</p><pre>doc/ libs/ .crystal/ .shards/ myproject</pre><p>Alternatively, if you want to keep your Docker image sizes as small as possible, you can use the aforementioned approach to build your Crystal project, then copy the binary out of the image, and simply add it to a plain debian image. This way you are not shipping your code and the Crystal compiler along with your application.</p><p>A word of caution if you run your project on <a href="https://cloud.docker.com/">Docker Cloud</a>: Crystal executables are blazingly fast, and they typically start up <em>before</em> Docker Cloud’s discovery services, which means that if your app container depends on a database container, it could happen that the app will not correctly resolve the database name as soon as it starts. Although your application should gracefully handle connection failures and retry after a reasonable timeout, an awful yet effective workaround for this issue is to just change the container CMD to add a sleep statement before actually starting the app.</p><p>We have been successfully running several Crystal apps in Docker with this approach, and it works like a charm, both setting them up in auto-builds or running them from a CI such as <a href="https://manas.tech/blog/2016/06/13/using-circleci-for-your-crystal-projects.html">CircleCI</a>. Let us know what your experience is if you try it out!</p><p><em>Originally published at </em><a href="https://manas.tech/blog/2016/09/28/running-crystal-on-docker.html"><em>manas.tech</em></a><em> on September 28, 2016.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d001196f1265" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using CircleCI for your Crystal projects]]></title>
            <link>https://medium.com/@manastech/using-circleci-for-your-crystal-projects-e7a239973d17?source=rss-e2d636f010c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/e7a239973d17</guid>
            <category><![CDATA[crystal-lang]]></category>
            <category><![CDATA[crystals]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[circleci]]></category>
            <category><![CDATA[continuous-integration]]></category>
            <dc:creator><![CDATA[ManasTech]]></dc:creator>
            <pubDate>Mon, 13 Jun 2016 16:08:00 GMT</pubDate>
            <atom:updated>2017-01-06T17:31:52.743Z</atom:updated>
            <content:encoded><![CDATA[<p>TL;DR We linked to a gist with the `circle.yml` example described in this post from <a href="https://github.com/crystal-lang/crystal/wiki#ci-integrations">Crystal’s wiki</a>.</p><p>One of the first things we do when we bootstrap a project at Manas is to set up a continuous integration server. Since in general we use <a href="https://github.com/">GitHub</a>, for open source projects <a href="https://travis-ci.org/">Travis</a> is a no brainer. However, we also work on a number of private repositories for which Travis has strong competition: <a href="https://circleci.com/">CircleCI</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*J_AhGE3FHzYl2P_S.png" /></figure><p>CircleCI offers a single CI container for unlimited private repositories on its free tier plan. It’s great if you are playing around with dozens of little projects that aren’t quite ready for primetime, but you still want to hold onto best practices without skyrocketing costs.</p><p>These days we’re exactly in that situation, experimenting with our beloved Crystal on a number of different applications.</p><p>You’d think using CircleCI to build applications that use <a href="http://devblog.avdi.org/2015/08/20/current-status/">novel programming languages like Crystal should make you hate your life</a>. Actually, it turns out to be a rather pleasant experience! Just add a circle.yml file to your project’s root directory with the contents below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/11bbfb65f07f344a2ed2640b494bb9aa/href">https://medium.com/media/11bbfb65f07f344a2ed2640b494bb9aa/href</a></iframe><p>A couple of remarks:</p><ul><li>Crystal doesn’t ship with the main Linux distributions (yet), neither is it natively supported by CircleCI (yet). That’s why we need to install it manually, as you can see in dependencies: pre:.</li><li>CircleCI uses Ubuntu, so you may be wondering why we don’t use <a href="http://crystal-lang.org/docs/installation/on_debian_and_ubuntu.html">Crystal’s official APT repository</a> instead of <a href="http://crystal-lang.org/docs/installation/from_a_targz.html">the self-contained tar.gz package</a>. The reason is that <a href="https://discuss.circleci.com/t/caching-apt-get-install-results/563">currently CircleCI’s cache doesn’t play well with APT</a> (see next bullet).</li><li>We’re taking advantage of <a href="https://circleci.com/docs/how-cache-works">CircleCI’s cache feature</a>, which significantly reduces build times if your dependencies don’t change often. We achieve that by listing Crystal’s target directory in dependencies: cached_directories: and then conditionally executing the installation commands in dependencies: pre:.</li><li>Again, since CircleCI currently doesn’t provide support Crystal out of the box, we need to tailor how tests get run. We just make sure to install shards before running (test: pre:) and then run the standard crystal spec command from test: override.</li></ul><p>That’s it! You now have no excuses to write beautiful, performant code in Crystal, resting safe on a robust continuous integration environment that has your back covered in case of regressions :).</p><p><em>Originally published at </em><a href="https://manas.tech/blog/2016/06/13/using-circleci-for-your-crystal-projects.html"><em>manas.tech</em></a><em> on June 13, 2016.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e7a239973d17" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A counting triangles story]]></title>
            <link>https://medium.com/@manastech/a-counting-triangles-story-71a15c543e0d?source=rss-e2d636f010c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/71a15c543e0d</guid>
            <category><![CDATA[web-apps]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[ManasTech]]></dc:creator>
            <pubDate>Mon, 18 Apr 2016 14:23:14 GMT</pubDate>
            <atom:updated>2016-04-18T14:23:14.309Z</atom:updated>
            <content:encoded><![CDATA[<p>Programming is a tool that can be used for a wide range of problems. Usually we code solutions for our clients, sometimes we build applications for ourselves. Programs don’t always need to be products at all, they can act as tiny pieces towards a larger objective.</p><p>It was back in May 2009 when <a href="http://manas.com.ar/staff/ndt/">Nico</a> came with a simple question. <strong>How many triangles can you find in this figure?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/0*x1S4Mtowp2EHsokL.png" /></figure><p>Obviously 1–3–10, 1–2–7 are triangles. For sure 7–9–2 is easy to depict. 2–4–6 is a bit small but definitely one to count and so on. Each of these triangles has another mirror image. After a little while, you realise there is also 1–2–6, and 2–6–7 and –oh boy!– 1–2–9. Most likely you will have lost count of how many triangles there are unless you are seriously organized.</p><p>Since we like having fun, either with arcades, drinks or whatever challenge comes to our daily life in Manas, we decided to tackle down this problem using our favorite tools.</p><p>In May 2009, some of us were nearing graduation, teaching assistants at college; school was another daily activity.</p><p>Most of us are programmers, and as such, we program. But each programmer has different preferences, backgrounds, areas of expertise, and this simple exercise was a perfect manifestation of that richness.</p><p>During the whole day a bunch of emails were sent with the proposed answers. Claims were made around 53, 54, 47, 63, 65. 47 was the most popular answer by far, yet, incorrect according to some sources.</p><p>The difference between the numbers is based on whether or not three aligned points shall be considered a triangle. And if 2–6–8 is equal to 2–8–10… definitely not the important thing here.</p><p>So the result was that we had lots of implementations, with completely different “mathematical” backgrounds to solve this riddle.</p><p>In chronological order we had the following solutions</p><ul><li><a href="http://manas.com.ar/staff/spalladino/">Santiago Palladino</a>, with <a href="https://github.com/manastech/triangles/blob/master/01-spalladino/triangles.py">62 lines of Python</a>, counted 3-segment cycles in a graph. Yep, he likes Python and Graph Theory (and Numerical Methods).</li><li><a href="http://manas.com.ar/staff/aromero/">Adrian Romero</a>, with <a href="https://github.com/manastech/triangles/blob/master/02-aromero/triangles2.py">35 lines of Python</a>, focused more on the lines than on the dots. He counted the intersections between pairs of lines that correspond to a triangle.</li><li><a href="http://manas.com.ar/staff/waj/">Juan Wajnerman</a>, with <a href="https://github.com/manastech/triangles/blob/master/03-waj/Triangles.cs">41 lines of C#</a> and heavy use of LINQ, took a relational algebra approach (or SQL-ish if Algebra is not your cup of tea) to get a cross product and filter, achieving the same answer as the previous ones.</li><li><a href="http://manas.com.ar/staff/bcardiff/">Brian J. Cardiff</a> (that’s me!) wrote a shameful and silly <a href="https://github.com/manastech/triangles/blob/master/04-bcardiff/triangulos.pl">30 lines of Prolog</a> (<a href="http://www.swi-prolog.org/pldoc/man?predicate=between/3">could have been 20</a>). Same answer! It was a Generate &amp; Test algorithm that searched for three not aligned points that were aligned in pairs.</li></ul><p>There were rounds of iteration along the day (we are agile developers after all) for fixing, discussing and discovering the different opinions around what is or isn’t a triangle. We relaxed the triangle criteria since we were not reaching the expected answer and we wanted to know why.</p><p>Adapting software is a big concern. If the inner functioning of the algorithm is not evident by reading the code, changing it is pretty hard. None of the above were too long or too cryptic, specially for the author himself. But, maybe because of my bias, Prolog was a clear winner here. Check the code!</p><p>But you know what? The solutions didn’t stop there.</p><ul><li><a href="http://manas.com.ar/staff/ary/">Ary Borenszweig</a> codes <a href="https://github.com/asterite">a lot</a>, <a href="https://github.com/crystal-lang/crystal/graphs/contributors">seriously</a>. Back then Crystal was not even a dream and he wrote <a href="https://github.com/manastech/triangles/tree/master/05-asterite">334 lines of Java</a>. He even created a <a href="https://github.com/manastech/triangles/blob/master/05-asterite/Triangles/src/asterite/triangles/Graph.java">Graph</a> class, <a href="https://github.com/manastech/triangles/tree/master/05-asterite/TrianglesTests/src/asterite/triangles/tests">tests</a> and<a href="https://github.com/manastech/triangles/blob/master/05-asterite/Triangles/src/asterite/triangles/TrianglesCounter.java">TrianglesCounter</a> class. It’s Java’s way. The idea behind it was similar to Adrian’s, focused on the lines.</li><li><a href="http://manas.com.ar/staff/jkicillof/">Jonathan Kicillof</a> (our graphic designer!) submitted his own. Although he knew ActionScript and today I am amazed about the Javascript plugins he is able to pull off, he submitted <a href="https://github.com/manastech/triangles/blob/master/06-jkicillof/65.pdf">a PDF</a>. Yeap, a well organized PDF that helped us point directly to the good, the bad and the ugly triangles.</li><li><a href="http://manas.com.ar/staff/ary/">Ary Borenszweig</a>, that guy that still codes a lot, submitted a total of <a href="https://github.com/manastech/triangles/tree/master/07-asterite-ui">676 lines of Java</a>. This time with a <a href="https://github.com/manastech/triangles/tree/master/07-asterite-ui/Triangles/src/asterite/triangles/ui">UI</a> to draw and solve any triangle based problem.</li></ul><p>Given that the input is fixed, the shortest program would be echo 47 but that would have taken all the fun out of it.</p><p>And it’s nice to use your skills and the computer to solve a problem for yourself, by yourself. I happily remember when I already had lots of fun and challenges programming with nothing but a <a href="http://www.annehelmond.nl/wordpress/wp-content/uploads/2007/11/logo_mit.png">turtle </a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=71a15c543e0d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Native Hackathon]]></title>
            <link>https://medium.com/@manastech/react-native-hackathon-58956a51c1cc?source=rss-e2d636f010c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/58956a51c1cc</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[ManasTech]]></dc:creator>
            <pubDate>Mon, 18 Apr 2016 14:20:56 GMT</pubDate>
            <atom:updated>2016-04-18T14:20:56.232Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>React Native Hackathon</strong></p><p>At Manas we organise internal hackathons on a monthly basis, with the goal to explore new technologies, languages, frameworks, paradigms, or whatever we want to play with; thus both satisfying our need to be constantly learning, and evaluating the tools that we will use for the projects to come.</p><p>We have tried ReactJS, Clojurescript, Phoenix, LISP, and, most recently, <a href="https://facebook.github.io/react-native/">React Native</a>. For every hackathon, the members who participated share with the rest of the team their findings and experience; this time, we decided to share it publicly here on the blog.</p><h3>The context</h3><p>It is worth mentioning that <a href="http://man.as/jedi">all</a> <a href="http://man.as/gus">of</a> <a href="http://man.as/palla">us</a> who were on this hackathon are primarily web developers, rather than mobile developers, and the browser is a much more familiar environment than Android or iOS. We all did have experience with javascript, and ReactJS to a minor extent.</p><p>Also, we are all Mac users, so the development was done on OSX and not Linux. We tested React Native <a href="http://facebook.github.io/react-native/releases/0.23/">version 0.23</a>.</p><h3>The what</h3><p>In one sentence, and from their homepage, React Native is a framework for building native web apps using React.</p><p>ReactJS is a javascript framework developed by Facebook, that brings a different programming model for building JS views; it is strongly based on componentisation, where each component is fundamentally a function that returns an HTML fragment from a model. Whenever there is a change in the model, the framework re-evaluates the view, calculates the diff with the current one using a virtual DOM, and enqueues the change operations on the actual DOM.</p><p>React Native uses the same approach, but instead of outputting HTML, it yields Android or iOS native components. The development is done in javascript as well, where each component yields an HTML-esque output, but using React Native wrappers for the actual native components instead of HTML nodes.</p><p>Skimming through the <a href="https://facebook.github.io/react-native/docs/tutorial.html#final-source-code">source code of their tutorial</a> should give you a good initial idea of how the framework works.</p><h3>The setup</h3><p>Though React Native requires a full Android and iOS development setup, plus all the actual React Native libraries, the <a href="https://facebook.github.io/react-native/docs/getting-started.html#content">setup</a> is surprisingly easy. Downloading all prerequisites, especially the Android SDK and XCode, might take a few hours if you hadn’t had downloaded them previously, but the configuration is pretty straightforward and powered by <a href="https://www.npmjs.com/">npm</a>.</p><h3>The experience</h3><p>We first went through the tutorial that covers the basics, and soon went on to implement an app of our own; we decided to work on a client app for reporting time to <a href="http://brium.me/">brium.me</a>.</p><p>As we worked on the apps, we found that the same philosophy used for developing web apps using React could be brought to the mobile environment with almost no friction.</p><p>The basic set of controls are easy to use and understand. Basic events, such as “clicks”, are managed via <a href="http://facebook.github.io/react-native/releases/0.23/docs/touchablehighlight.html#content">Touchable</a> wrappers to standard controls. Styling inside javascript did not feel out of place, and the properties felt familiar; also, the Flexbox layout system follows the same rules as the CSS one.</p><p>Even though React Native does not attempt to be a write-once use-everywhere solution, and encourages you to write different interfaces for iOS and Android, sharing only the common business logic, we found that for a simple application we could use exactly the same codebase, since the React Native wrappers over the basic components are the same for both platforms.</p><p>Running and debugging the code was surprisingly easy. Simple command-line commands allow you to start either the iOS or Android version in an emulator, and once the app is running, it just needs to connect to the local dev server to download the new JS bundle to be executed, thus greatly speeding up the compile/run cycle. Debugging is done by attaching the app to a Chrome page, and using its own — already familiar — developer tools for going through the javascript code. Running the app on an Android phone was also easy to do, and once initially set up via USB, switching to Wifi to update the JS bundle was painless, always allowing for the same reloading and debugging practices as with the emulator.</p><h3>The bad and the ugly</h3><p>React Native still hasn’t reached its 1.0 milestone, and we did stumble upon a few killer bugs. Attaching the debugger to an Android emulator changed the behaviour of the Fetch API, requiring an extra user interaction to actually return the result of a request, something that took us a few hours to figure out; fortunately, this <a href="https://github.com/facebook/react-native/issues/6679">issue</a> has been already identified and solved in the upcoming version. Also, we could not run the app on the iOS emulator or deploy to an iPhone <em>unless</em> Chrome debugging was running, something that has also been<a href="http://stackoverflow.com/questions/30295923/when-using-react-native-why-does-my-iphone-or-emulator-hang-with-a-white-screen">reported by others</a>.</p><p>Documentation on some modules is scarce (see the Flexbox polyfill <a href="http://facebook.github.io/react-native/releases/0.23/docs/flexbox.html#content">docs</a> for instance), but being open source, we could always fall back to the source code to figure things out; so lack of docs was not a showstopper at any point.</p><h3>The missing pieces</h3><p>Being a one-day event, we missed several features of the framework that we would have liked to evaluate, such as bindings to native code, local storage, notifications, background operations and access to specific phone services such as geolocation.</p><p>We would also have liked to try React Native in combination with another framework, such as <a href="https://github.com/reactjs/redux">Redux</a>, in the context of a larger app — but this can be the goal of a future hackathon.</p><h3>The conclusion</h3><p>Clearly a thumbs-up for React Native. We had already fell for the development model introduced by React, and being able to carry that model almost directly the the mobile environment is immensely powerful, especially taking into consideration the implementation of applications across mobile browsers, Android and iOS apps.</p><p>Use in production still feels a bit risky at this point, considering some of the bugs we faced, but we cannot rule out the possibility that with some additional time we could have worked around them.</p><p>All in all, React Native looks like a fantastic tool for implementing mobile apps, especially for developers coming from the web world.</p><p>You can check out the code of the app we implemented <a href="https://github.com/spalladino/brium-client-react-native">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=58956a51c1cc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Let’s Encrypt certificate auto-renewal in docker-powered nginx reverse proxy]]></title>
            <link>https://medium.com/@manastech/let-s-encrypt-certificate-auto-renewal-in-docker-powered-nginx-reverse-proxy-1b1d275595ff?source=rss-e2d636f010c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b1d275595ff</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[ssl]]></category>
            <dc:creator><![CDATA[ManasTech]]></dc:creator>
            <pubDate>Tue, 26 Jan 2016 17:08:51 GMT</pubDate>
            <atom:updated>2016-01-26T17:08:51.290Z</atom:updated>
            <content:encoded><![CDATA[<p>If you have been following our blog, you’ll know that sometimes we blog about<a href="http://stg.manas.com.ar/blog/2016/01/18/a-new-year-s-puzzle.html">events</a>, sometimes about <a href="http://stg.manas.com.ar/blog/2015/12/23/codegames-the-force-awoke.html">projects</a>, sometimes about <a href="http://stg.manas.com.ar/blog/2015/11/19/voices-of-youth-workshop.html">travels</a>, and sometimes about highly technical and very specific stuff. I hope that by the title of the article you have easily figured out which one is the case this time.</p><h3>The context</h3><p>During the last year we have been migrating much of our infrastructure to<a href="https://www.docker.com/">Docker</a> containers, as we have mentioned in <a href="http://stg.manas.com.ar/blog/2015/12/15/logging-for-rails-apps-in-docker.html">other posts</a>. In our particular setup, we run several small containers in each host, and have a reverse nginx proxy, running in Docker as well, to route client requests to the corresponding app.</p><p>Another component we’ve been introducing to our infrastructure are certificates powered by <a href="https://letsencrypt.org/">Let’s Encrypt</a>, a brand new CA that provides free SSL certificates to promote secure connections along the web. Let’s encrypt certificates are valid for 90-days, and the service encourages you to automate the renewal process.</p><h3>Options for automation</h3><p>Let’s encrypt provides <a href="http://letsencrypt.readthedocs.org/en/latest/using.html#installation">several options</a> for automating certificate installation in the form of <a href="http://letsencrypt.readthedocs.org/en/latest/using.html#installation">plugins</a>. However, none of the options available allowed us to fully automate the process without any disruption to any of the services, and without requiring changes to the Docker images we were using for our apps or for the nginx.</p><h3>Running with Docker</h3><p>One of the options for installing certificates provided by Let’s Encrypt is a<a href="https://quay.io/repository/letsencrypt/letsencrypt">Docker image</a>, but it <a href="http://letsencrypt.readthedocs.org/en/latest/using.html#running-with-docker">involves some limitations</a> as it is:</p><blockquote>Docker is an amazingly simple and quick way to obtain a certificate. However, this mode of operation is unable to install certificates or configure your webserver, because our installer plugins cannot reach it from inside the Docker container.</blockquote><p>In other words, you can use the Docker container to download the certificate, but the actual install process requires a manual step.</p><h3>Install certificates in the nginx container</h3><p>The solution we devised together with <a href="http://stg.manas.com.ar/staff/waj">Juan</a> for this was defining a volume/etc/letsencrypt in the nginx proxy container where the certificates are stored, and <em>mounting that volume in the Let’s Encrypt Docker container</em> via thevolumes-from switch, so the certificates are automatically reachable by the proxy.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/771a6396111cd915c54dcb41e7a4c7d7/href">https://medium.com/media/771a6396111cd915c54dcb41e7a4c7d7/href</a></iframe><p>The last line in the script sends a SIGHUP to the nginx container so it reloads its configuation as needed.</p><p>The folder PROXY_DIR/www/DOMAIN, one for each domain, is used to store the proof file generated by letsencrypt. We mount the entire PROXY_DIR/www/folder in /var/www in the proxy container, so it can serve the proof files, and route the requests for it to the local directory instead of forwarding them to the application in the nginx configuration, once for each upstream $host defined:</p><pre><em># Statically serve all files in .well-known, which is the location where letsencrypt stores the proof file</em><br>location /.well-known/ <strong>{</strong><br>    root /var/www/<strong>{{</strong> $host <strong>}}</strong>;<br><strong>}</strong></pre><pre><em># And proxy_pass all the remaining requests as usual</em><br>location / <strong>{</strong><br>    proxy_pass http://<strong>{{</strong> $host <strong>}}</strong>;<br>    proxy_set_header Host $http_host;<br>    proxy_set_header X-Real-IP $remote_addr;<br>    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;<br>    proxy_set_header X-Forwarded-Proto $scheme;</pre><pre>    <em># HTTP 1.1 support</em><br>    proxy_http_version 1.1;<br>    proxy_set_header Connection &quot;&quot;;<br><strong>}</strong></pre><p>As a side note, the notation you see in the snippet above is go templating language, as we use <a href="https://github.com/jwilder/docker-gen">docker-gen</a> to dynamically generate the <a href="https://github.com/jwilder/docker-gen/blob/master/templates/nginx.tmpl">nginx configuration</a>.</p><h3>Automate all the things</h3><p>The letsencrypt.sh snippet is added to cron.monthly, so certificates are renewed on a monthly based. This can be set up once per every domain to be registered in letsencrypt in the server, as each renewal does not interfere with the other.</p><p>A word of caution though: Let’s Encrypt currently imposes <a href="https://community.letsencrypt.org/t/rate-limits-for-lets-encrypt/6769">severe restrictions</a> to the number of certificates per domain it issues per week, so if you are modifying and testing this setup several times, you may find yourself locked out the platform.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b1d275595ff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A New Year’s Puzzle]]></title>
            <link>https://medium.com/@manastech/a-new-year-s-puzzle-72b452982860?source=rss-e2d636f010c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/72b452982860</guid>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[ManasTech]]></dc:creator>
            <pubDate>Tue, 19 Jan 2016 14:13:28 GMT</pubDate>
            <atom:updated>2016-01-19T14:14:00.309Z</atom:updated>
            <content:encoded><![CDATA[<p>Every six months everyone at Manas gather for a review. In this review, among other things, <a href="https://manastech.gitbooks.io/handbook/content/en/11-compensacion/0-compensacion.html">we decide the salary raises for everyone</a>. In this process everyone decides how to split the available raise money between everyone else in the team. Then the effective raise you get is the average of the sum of amounts everybody else gave you.</p><p>For this, we made a web app that we run locally. You get to see everyone else in a list, and a text input next to each one where you choose the amount. But also, there are small links to leave anonymous comments to others, which you get to see when the process finishes. These comments usually end up being “Awesome work this time!” or “I really liked you doing this and that”, or something funny, sometimes signed by the one who wrote them to remove that anonymity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PGxweTAhW_Bt6_2DgnveUw.png" /></figure><p>A few days before this last year’s review an idea came to my mind: could I somehow use those anonymous comments to make a puzzle that everyone, together, has to solve?</p><p>I’ll first tell you how it went, so you get a chance to almost experience the puzzle. Then I’ll write about the puzzle’s design process, followed by some conclusions.</p><h3>Playing the puzzle</h3><p>The last click that decides how to split the raise amounts have been given, and everyone had in their screen the final results, together with some anonymous comments. After a small silence some began to laugh and say “What’s this?” and “Who’s the funny one?”. Soon, everyone realized that they received a mysterious comment. It read like this: “Your number is Fernando’s number plus 17”, or “Your number is the sum of Santiago’s number plus Fernando’s number plus Valeria’s number minus 123”.</p><p>Because you can’t give yourself an anonymous comment, they started asking others to show their screen and check if they received the comment. They initially suspected <a href="http://manas.com.ar/staff/ndt/">Nico</a> and me, but we both had the mysterious messages as well. There was someone else: <a href="http://manas.com.ar/staff/mdavid/">Maria</a> couldn’t be at the same place, but still did the review process and said that she didn’t receive a comment like that. Could she be the one behind all of this? She said “No”. Nobody knew what to believe, but at the same time were thinking about the equations.</p><p>At first people though a big system of equations was needed to be solved, but they soon realized this wasn’t the case, as, for example, <a href="http://manas.com.ar/staff/fjabalera/">Fernando</a>’s, <a href="http://manas.com.ar/staff/spalladino/">Santiago</a>’s,<a href="http://manas.com.ar/staff/vtiffenberg/">Valeria</a>’s and <a href="http://manas.com.ar/staff/bcardiff">Brian</a>’s numbers depended exclusively on the numbers of others in that smaller group. In short, there were five system of equations to solve.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c-jOkxJafCWE3ArAsUIvUQ.png" /></figure><p><a href="http://manas.com.ar/staff/ggiraldez">Gustavo</a> began to solve one, and Valeria another one. After a couple of minutes Gustavo had a first answer: “My number is 115, <a href="http://manas.com.ar/staff/waj">Juan</a>’s is 108, <a href="http://manas.com.ar/staff/mverzilli">Martin</a>’s is also 108 and Mauricio’s is 111.” Then Valeria finished solving theirs, but her numbers were “37.5” and others with a decimal point. She said “This isn’t right” and checked the instructions again and found a mistake, so she redid it and ended with “good” numbers like 33, 101, 110 and 115.</p><p>Valeria’s instructions also said “Also, your number is the last one in my list.” Her number is 33, so she thought “Maybe it’s the smallest one.”</p><p>Some started wondering what these numbers meant. Some jokes were said, but nobody had an idea.</p><p>After a while Juan said: “These are definitely ASCII codes”. So 115 is ’s’, 108 is ‘l’, 111 is ‘o’ and so on. “But how do we order them?”, asked Nico. And then he remembered: “Valeria, your instructions said that your number was the last one in the list, right? Anyone has the first one?”. It turned out <a href="http://manas.com.ar/staff/aromero">Adrian</a>’s instructions said so. Somebody said “So maybe the order is lexicographic?”</p><p>Brian opened his notebook and wrote the list of names, together with their given number and ASCII letter equivalent. It began to read “s__aMs__si_uoy__ttseb!”. They were puzzled, that didn’t make sense. But soon someone realized the words were reversed: the last letters “tseb” are “best”. And probably “s__aM” is “Manas”! After solving one more system of equations and deducing the rest of the letters, it read “sanaMsehsiwuofehttseb!”. They still couldn’t understand exactly the meaning, as reading it in reverse it says “best the fou wishes Manas!”</p><p>At that point I said “Time out!” and told them I made the puzzle, that the “f” was wrong (somebody wrote somebody else’s number wrong), that it was a “y”, and so they realized it reads (if you also reverse the word order): “Manas wishes you the best!”. “Awwwww…”, everyone said, in a cute tone.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5G4hgEO40d8ySRDDBKYHlA.png" /></figure><p>(As a side note, the original message was “Manas les desea lo mejor!”, in Spanish, but I translated the message for the article.)</p><h3>Designing the puzzle</h3><p>I recently played a lot of puzzle games: The Talos Principle, Antichamber, Braid, Snakebird and Fez. The idea of giving everyone a letter, encoded in ASCII, immediately came to my mind.</p><p>I needed a message. Ideas like “At Manas we solve problems” came to my mind, which would have been kind of fun and recursive, but in Spanish that has long words that would be easy to find, even if not all of the equations were solved, so I opted for “Manas les desea lo mejor!”, which has shorter words and has the number of letters I needed.</p><p>There was a problem: I had a feeling that not everyone was going to solve their puzzle, only because I couldn’t just hope that everyone would be in the mood for that. I also wanted there to be interaction between the participants, so they could help each other and feel they are working together towards one goal. A system of equations seemed like a good fit for this. But, solving a huge system was going to be tedious and take a lot of time (if done manually, and I wanted it to be done like that, a reminiscence), so I decided to make smaller groups. The systems were all simple, like:</p><pre>A = B + 11<br>B = C + 13<br>C = D - 23<br>D = A + B + C - 111</pre><p>In this way you could replace values from the first equations in the next ones and find the solution. I didn’t care that it was relatively simple: the real puzzle, the needed “jump”, was noticing that these numbers were ASCII codes.</p><p>Then, of course, an ordering of the codes was missing. Lexicographical order seemed good too, so I gave a couple of clues about this. I originally decided to give an extra clue saying who is the second one in the list, but finally decided to have high hopes about my friends, and that they would solve this extra “jump”.</p><p>Finally, I wanted to introduce a last “jump”: the words and letters wouldn’t be ordered in the usual order, so they would have to realize this.</p><p>In total, three jumps were needed: ASCII codes, order of the codes, and order of the letters/words. Would they make it to the end?</p><p>In any case, the experiment was interesting: would they start solving the equations, or just leave them on the screen? And how many jumps would they accomplish? Would they like it?</p><p>At the review, the moment I started writing the anonymous comments I noticed a flaw: I couldn’t leave a comment to myself, they would find it was me. I thought about discarding the whole plan, but then an idea came to my mind: I could open the developer’s console and replace one of the comments I received with the puzzle instructions. I decided to do this, and as soon as the review was over did it, and luckily, because they asked me to show my screen!</p><p>As they solved the puzzles I decided to join and help them. It was tough, because I had to pretend I didn’t know anything about it.</p><h3>Conclusion</h3><p>It was really awesome to see everyone having fun, laughing and thinking about possible solutions and meanings.</p><p>Some days after the puzzle was over I asked Gustavo and Valeria if, at the moment when they found out their numbers, they thought the numbers had a second meaning. They both said “No”, that they took that as a challenge, something to solve. I think that’s nice, to do something without expecting a reward of some kind, just for the fun of it.</p><p>I also thought about what would have happened if I introduced the puzzle without the mystery surrounding it. Would they still want to solve it? Valeria said “Come on, you know us. You know we would have wanted to solve it.”</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=72b452982860" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Switching Rails database per git branch]]></title>
            <link>https://medium.com/@manastech/switching-rails-database-per-git-branch-83350671186b?source=rss-e2d636f010c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/83350671186b</guid>
            <dc:creator><![CDATA[ManasTech]]></dc:creator>
            <pubDate>Fri, 08 Jan 2016 17:26:29 GMT</pubDate>
            <atom:updated>2016-01-08T17:26:29.645Z</atom:updated>
            <content:encoded><![CDATA[<p>Working with the <a href="http://nvie.com/posts/a-successful-git-branching-model/">git-flow</a> pattern in an application involves a lot of switching back and forth along several branches. Whether it is implementing a new feature in a dedicated branch, applying a hotfix to a deployed version, or making the final touches to a release candidate, it is most likely that these switches involve moving between different schema versions. This implies that when you switch back to an older version, your current development database might have changes that were not present in that version, which you’d need to roll back.</p><p>Since setting up a development database with some testing data is a process that might take some time, even if you have fully automated it, destroying the database and recreating from scratch is not a very appealing option. Another option, running db:rollback to the target version, can be cumbersome, and will probable cause data loss that you’ll need to recreate when switching back to the most recent versions.</p><p>A better option is to <a href="http://mislav.net/rails/branching-the-database-along-with-your-code/">keep one database per branch</a>, so each branch has its own copy of the development schema and data. To accomplish this, an easy way is to modify your database.yml to look for a database based on the branch name:</p><pre>&lt;%<br>  require &#39;config&#39;<br>  branch = `git rev-parse --abbrev-ref HEAD`.strip rescue nil<br>  use_single_db = !Settings.db_per_branch || !branch || branch == &#39;master&#39;<br>  branch_spec = (use_single_db ? &quot;&quot; : &quot;_#{branch}&quot;).underscore.gsub(/[\.\/\-]/, &#39;_&#39;)<br>%&gt;<br><br>development:<br>  &lt;&lt;: *default<br>  database: app_development&lt;%= branch_spec %&gt;</pre><p>Note that here we’re turning on this feature only if a <a href="https://github.com/railsconfig/config#developer-specific-config-files">local setting</a> is set, so this feature is actually opt-in. You can also use environment variables or git config variables.</p><p>In order to easily set up the branch database, we added a rake task that automatically copies the current development database into the branch database if it doesn’t exist:</p><pre>namespace :db do<br><br>  desc &quot;Copies master development database, or specified by SOURCE env param, into current branch name only if it does not exist&quot;<br>  task :clone do<br>    config = Rails.application.config.database_configuration[Rails.env]<br>    source_db = ENV[&#39;SOURCE&#39;].presence || &#39;app_development&#39;<br>    target_db = config[&#39;database&#39;]<br>    mysql_opts =  &quot;-u #{config[&#39;username&#39;]} &quot;<br>    mysql_opts &lt;&lt; &quot;--password=\&quot;#{config[&#39;password&#39;]}\&quot; &quot; if config[&#39;password&#39;].presence<br><br>    `mysqlshow #{mysql_opts} #{target_db.gsub(&#39;_&#39;, &#39;\\\\\_&#39;)}`<br>    raise &quot;Target database #{target_db} already exists&quot; if $?.to_i == 0<br><br>    `mysqlshow #{mysql_opts} #{source_db.gsub(&#39;_&#39;, &#39;\\\\\_&#39;)}`<br>    raise &quot;Source database #{source_db} not found&quot; if $?.to_i != 0<br><br>    puts &quot;Creating empty database #{target_db}&quot;<br>    `mysql #{mysql_opts} -e &quot;CREATE DATABASE #{target_db}&quot;`<br><br>    puts &quot;Copying #{source_db} into #{target_db}&quot;<br>    `mysqldump #{mysql_opts} #{source_db} | mysql #{mysql_opts} #{target_db}`<br>  end<br><br>end</pre><p>Thus, by running rake db:clone after switching to a new branch, the branch database is automatically created based on the current master development database; you can also specify a different SOURCE database depending on where you’re branching from. You can also automate this by adding a git hook to perform this task every time you switch branches, if you find yourself forgetting a little too often to recreate the database branch.</p><p>There are multiple alternatives to this approach, such as keeping the database data in dump file and always using the app_development database (see <a href="https://github.com/room118solutions/git-rails-database-branch-hook">here</a>). Still, this approach has been working great for us so far. Let us know which works best for you and your team!</p><p>Want to say anything? Reach <a href="https://twitter.com/intent/tweet?url=http%3A%2F%2Fmanas.com.ar%2Fblog%2Fdrafts%2Fend-of-2015-infographic.html&amp;text=@manastech&amp;related=manastech">@manastech</a> on Twitter!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83350671186b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Logging for Rails apps in Docker]]></title>
            <link>https://medium.com/@manastech/logging-for-rails-apps-in-docker-3f195a9839b4?source=rss-e2d636f010c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f195a9839b4</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[rails]]></category>
            <dc:creator><![CDATA[ManasTech]]></dc:creator>
            <pubDate>Tue, 22 Dec 2015 15:10:39 GMT</pubDate>
            <atom:updated>2015-12-22T15:11:35.511Z</atom:updated>
            <content:encoded><![CDATA[<p>We can all agree that logging is key in every setup: having useful logs from the components in your environment is your best tool in diagnosing issues and keeping track of the health of your applications. Of course, Docker-based deployments are no exception to this rule. In this post we will go through the options we have evaluated for configuring logging in Rails-based docker stacks, upon reaching an <a href="https://www.elastic.co/videos/introduction-to-the-elk-stack">ELK stack</a>.</p><h3>You are doing it wrong</h3><p>First of all, a piece of advice: regardless of the kind of solution you are looking forward to implement, <strong>if you have done nothing to tweak your application’s logging, you are doing something wrong</strong>.</p><p>Rails apps will log to a local /log folder within the container. This means that logs will not be rotated, and will not be kept if the container is recreated. Access to logs is also cumbersome as it requires accessing the running container.</p><h3>Mounted volume</h3><p>The easiest way to work around this is to mount a host volume in your/app/log container folder, in order to persist log files and access them directly from the host. Rotation can be handled externally through <a href="http://www.linuxcommand.org/man_pages/logrotate8.html">logrotate</a>configurations, using a copytruncate strategy to avoid having to signal the running Rails process.</p><h3>Docker logging drivers</h3><p>But we can do better. Docker provides <a href="https://docs.docker.com/engine/reference/logging/overview/">logging drivers</a> for your containers right out of the box; though the default is a JSON file, it has support for syslog,journald, gelf, fluentd and awslogs.</p><p><em>As a side note, keep in mind that unless explicitly configured, the json-filedefault logging driver </em><strong><em>will not rotate your log files</em></strong><em>, which will grow indefinitely.</em></p><p>Docker will manage whatever your applications log to STDOUT; this means that we need to route the Rails logs to standard output rather than to a local file.</p><h3>Tuning your Rails app</h3><p>The most straightforward option is to simply set your Rails logger to write to STDOUT, so all log entries are redirected to the Docker logging driver.</p><pre>config.<strong>logger</strong> <strong>=</strong> Logger.<strong>new</strong>(STDOUT)</pre><p>However, if you want to post-process your log entries to search through them or extract metrics, as we will be doing later, you will find the typical Rails logger format a bit cumbersome to parse, especially considering that each request spans several lines.</p><p>Luckily, there is already a gem out there named <a href="https://github.com/roidrage/lograge">lograge</a>, which will take care of this by automatically reformatting your logs, and redirecting them to STDOUT as well.</p><p>So, instead of this:</p><pre>Started GET &quot;/&quot; for 127.0.0.1 at 2012-03-10 14:28:14 +0100<br>Processing by HomeController#index as HTML<br>  Rendered text template within layouts/application (0.0ms)<br>  Rendered layouts/_assets.html.erb (2.0ms)<br>  Rendered layouts/_top.html.erb (2.6ms)<br>  Rendered layouts/_about.html.erb (0.3ms)<br>  Rendered layouts/_google_analytics.html.erb (0.4ms)<br>Completed 200 OK in 79ms (Views: 78.8ms | ActiveRecord: 0.0ms)</pre><p>You get this:</p><pre>method=GET path=/jobs/833552.json format=json controller=jobs action=show status=200 duration=58.33 view=40.43 db=15.26</pre><p>Just add the lograge gem to your app and set:</p><pre>config.<strong>lograge</strong>.<strong>enabled</strong> <strong>=</strong> <strong>true</strong></pre><h3>Going through logstash</h3><p>Since we are now successfully running our log entries through Docker, we have to decide where to send them. Here we will set up a simple ELK stack, in which we will send the log entries to Logstash to be processed, which will in turn store them in an ElasticSearch, and use Kibana for visualisations.</p><p>First step is to have our Rails app output log entries in a logstash-compatible format. Since we are using lograge, we can easily add support for logstash by adding the logstash-event gem and configuring:</p><pre>config.<strong>lograge</strong>.<strong>formatter</strong> <strong>=</strong> Lograge<strong>::</strong>Formatters<strong>::</strong>Logstash.<strong>new</strong></pre><p>Then we need to actually set up the ELK stack. We’ll use the following docker-compose configuration:</p><pre>elasticsearch:<br>  image: elasticsearch:2.0<br>  command: elasticsearch -Des.network.host=0.0.0.0</pre><pre>logstash:<br>  image: logstash:2.0<br>  command: logstash -f /etc/logstash/conf.d/logstash.conf<br>  ports:<br>    - &quot;12201:12201/udp&quot;<br>  volumes:<br>    - &quot;./logstash:/etc/logstash/conf.d&quot;<br>  links:<br>    - elasticsearch</pre><pre>kibana:<br>  image: kibana:4.2<br>  links:<br>    - elasticsearch<br>  ports:<br>    - &quot;5601:5601&quot;</pre><p>Note that we are mounting a logstash configuration file, which instructs logstash to receive entries via gelf (Graylog Extended Log Format, one of the docker-supported drivers), parse our JSON-formatted log entries to extract all the metadata contained, and store the result in the ElasticSearch host:</p><pre>input {<br>  gelf {}<br>}</pre><pre>filter {<br>  json {<br>    source =&gt; &quot;short_message&quot;<br>    remove_field =&gt; &quot;short_message&quot;<br>  }<br>}</pre><pre>output {<br>  elasticsearch {<br>    hosts =&gt; &quot;elasticsearch:9200&quot;<br>  }<br>}</pre><p>Last step is to instruct our docker containers to actually use this logging drivers. Simply use the following config in the docker-compose for your apps:</p><pre>log_driver: gelf<br>log_opt:<br>  gelf-address: udp://IP_TO_LOGSTASH_HOST:12201</pre><p><em>You can also specify these options as defaults in the DOCKER_OPTS for your docker daemon, so they apply to all your containers.</em></p><h3>Show me the code</h3><p>We have uploaded a fork of a <a href="https://github.com/waj/sample_app_rails_4">sample Rails app</a> with the <a href="https://github.com/waj/sample_app_rails_4/commit/eea2b1be2a5a834bbffebbca418235dbb5562287">lograge configuration</a>and a simple <a href="https://github.com/waj/sample_app_rails_4/commit/60d5694c29dbf239bc2aa375be9603f0b12d10b5">Dockerfile</a>, as well as the <a href="https://github.com/waj/elk-demo">configuration for the ELK stack</a>.</p><p>Together with <a href="http://manas.com.ar/staff/waj">Juan</a>, with whom we set up this configuration, we gave a presentation on the 7th Buenos Aires Docker Meetup. You can find the slides <a href="http://www.slideshare.net/santiagopalladino/logging-in-docker">on Slideshare</a> or watch the recorded presentation in Spanish <a href="https://www.youtube.com/watch?v=rxsn9BjtuL4">on YouTube</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f195a9839b4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>