<?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:media="http://search.yahoo.com/mrss/"><channel><title><![CDATA[Pedro Medeiros]]></title><description><![CDATA[Pedro Medeiros]]></description><link>http://blog.pemedeiros.com/</link><generator>Ghost 0.7</generator><lastBuildDate>Wed, 15 Nov 2023 09:09:37 GMT</lastBuildDate><atom:link href="http://blog.pemedeiros.com/rss/" rel="self" type="application/rss+xml"/><ttl>60</ttl><item><title><![CDATA[Elixir atoms are everywhere]]></title><description><![CDATA[<p>In elixir-lang we have a primitive called atom. Atoms are nothing more than a constant string that behaves very differently compared to strings. When we declare an atom literal in our code, the Erlang VM checks if it is already in memory and reuses it. On the other side when</p>]]></description><link>http://blog.pemedeiros.com/elixir-atoms-are-everywhere/</link><guid isPermaLink="false">47e104d8-a37a-4427-af7b-1fe5358aba74</guid><dc:creator><![CDATA[Pedro Medeiros]]></dc:creator><pubDate>Wed, 17 May 2017 04:01:40 GMT</pubDate><media:content url="http://blog.pemedeiros.com/content/images/2017/05/atom_img1.jpg" medium="image"/><content:encoded><![CDATA[<img src="http://blog.pemedeiros.com/content/images/2017/05/atom_img1.jpg" alt="Elixir atoms are everywhere"><p>In elixir-lang we have a primitive called atom. Atoms are nothing more than a constant string that behaves very differently compared to strings. When we declare an atom literal in our code, the Erlang VM checks if it is already in memory and reuses it. On the other side when a code with strings are evaluated it allocates a new string in memory to be passed on. It works just like ruby's symbols.</p>

<p>To show how it really works let's write some code and see how it performs using a tool called <a href="https://tkowal.wordpress.com/2016/04/23/observer-in-erlangelixir-release/">observer</a>. On elixir terminal we can just fire <code>:observer.start()</code> and go to the tab called <code>memory allocation</code>. So for some fun we can write a simple comprehension code that creates a really huge list full of string with the same value.</p>

<pre><code class="language-elixir-lang">iex(1)&gt; for _ &lt;- 1..1_000_000, do: "string"  
</code></pre>

<p>After executing this code we can see that we created a huge list with a million strings with the value <code>string</code> and we can notice the the memory of our erlang code just grew a lot. On my machine I just allocated about 225 mb.</p>

<p><img src="http://blog.pemedeiros.com/content/images/2017/05/string_allocation.png" alt="Elixir atoms are everywhere"></p>

<p>If we run the code again but with atoms instead of strings we can see that we have a very different reality. </p>

<pre><code class="language-elixir-lang">iex(1)&gt; for _ &lt;- 1..1_000_000, do: :string  
</code></pre>

<p>Just 60 mb was allocated. It happens because we still had to allocate the list that was generated during the comprehension command.</p>

<p><img src="http://blog.pemedeiros.com/content/images/2017/05/symbol_alocation.png" alt="Elixir atoms are everywhere"></p>

<p>The main difference is that with strings we really allocated one million strings and we put them into a list. And with atoms we just allocated the value once and we put the reference of this value a million times into the list. Which is a sweet difference.</p>

<h4 id="atomslimitations">Atoms Limitations</h4>

<p>Using atoms to reuse memory is nice, but there's a limitation. The Erlang vm stores the Atom inside a table internally and has a default limit of 1048576 atoms per instance. This value can be <a href="http://erlang.org/doc/man/erl.html#+t">configured</a>, but in the end it is not an optimization that we want to make.</p>

<h4 id="othercooluses">Other cool uses</h4>

<p>Elixir atoms are not meant to use as constant. In fact they are used to name somethings on the language, such as</p>

<h6 id="1booleanvalues">1. Boolean Values</h6>

<p>Erlang there is no boolean values like other languages. But to represent boolean values it utilizes two special atoms that are <code>true</code> and <code>false</code>. Because erlang atoms are just words that starts with lowercase letters this representation suits well.</p>

<pre><code class="language-erlang">1&gt; 1 == 1.  
true  
</code></pre>

<p>But on elixir expands the usage of true and false to be used also without the colon (<code>:</code>).</p>

<pre><code class="language-elixir-lang">iex(1)&gt; true == :true  
true  
iex(2)&gt; false == :false  
true  
iex(3)&gt; is_atom(:false)  
true  
</code></pre>

<h6 id="2modulenames">2. Module Names</h6>

<p>Module names are also a representation of an atom. just to see the way we call erlang code on elixir. For example using the erlang <a href="http://erlang.org/doc/man/math.html">math module</a> to calculate the square root.</p>

<pre><code class="language-elixir-lang">iex(1)&gt; :math.sqrt(16)  
4.0  
</code></pre>

<p>We always call our functions by using atoms to to name the modules. We can see that on elixir by calling the funciton <code>is_atom/1</code> on any elixir module such as <code>GenServer</code>. Notice also that on elixir if a token starts with upcase it is translated directly to atom, so it's possible to declare an atom with upcase value without using colons.</p>

<pre><code class="language-elixir-lang">iex(1)&gt; is_atom(GenServer)  
true  
iex(2)&gt; is_atom(RandomName)  
true  
iex(1)&gt; RandomName == :'Elixir.RandomName'  
true  
</code></pre>

<p>Now that we know that module names are just atoms, we can define modules with a lowercase name just by using an atom with a colon.</p>

<pre><code class="language-elixir-lang">defmodule :hello do  
  def say_to(name \\ "World") do
    "Hello #{name}"
  end
end  
</code></pre>

<pre><code class="language-elixir-lang">iex(1)&gt; :hello.say_to("John")  
"Hello John"
</code></pre>

<h4 id="conclusion">Conclusion</h4>

<p>Atoms uses very little memory and are unique across all the erlang node, using it to name modules and defining booleans values are a really smart approach. But they have very limited usage, it's not recommended to use atoms on the go for everything but for values that defines codes they are useful.</p>]]></content:encoded></item><item><title><![CDATA[weekly picks 07/10]]></title><description><![CDATA[<p>This post is about how it feels to learn JavaScript in 2016. JavaScript sure got a lot better over the time but we are a little close to the edge of insanity IMO.</p>

<p><a href="https://hackernoon.com/how-it-feels-to-learn-javascript-in-2016-d3a717dd577f#.r1tzvvyb8">https://hackernoon.com/how-it-feels-to-learn-javascript-in-2016-d3a717dd577f#.r1tzvvyb8</a></p>

<p>From hacker news, what's your favorite tech talk? I love tech talks,</p>]]></description><link>http://blog.pemedeiros.com/weekly-picks-2/</link><guid isPermaLink="false">ce0ef64b-baf7-4f37-a343-8d2d99f9f86c</guid><dc:creator><![CDATA[Pedro Medeiros]]></dc:creator><pubDate>Sun, 09 Oct 2016 15:58:46 GMT</pubDate><content:encoded><![CDATA[<p>This post is about how it feels to learn JavaScript in 2016. JavaScript sure got a lot better over the time but we are a little close to the edge of insanity IMO.</p>

<p><a href="https://hackernoon.com/how-it-feels-to-learn-javascript-in-2016-d3a717dd577f#.r1tzvvyb8">https://hackernoon.com/how-it-feels-to-learn-javascript-in-2016-d3a717dd577f#.r1tzvvyb8</a></p>

<p>From hacker news, what's your favorite tech talk? I love tech talks, I try to watch at least 3 new each week this hacker news post will be on my favs tab for a couple of weeks. <br>
<a href="https://news.ycombinator.com/item?id=12637239&amp;utm_source=hackernewsletter&amp;utm_medium=email&amp;utm_term=ask_hn">https://news.ycombinator.com/item?id=12637239&amp;utm<em>source=hackernewsletter&amp;utm</em>medium=email&amp;utm<em>term=ask</em>hn</a></p>

<p>Code wars now supports Elixir This is the best news ever! I'm a great enthusiastic from Elixir and codewars. Gonna make some of their katas on elixir and contribute with new ones for sure <br>
<a href="http://www.codewars.com/">http://www.codewars.com/</a></p>

<p>Talking about Elixir this blog post covers how to monitor and Phoenix application in 2016. Nice for those who deploying your elixir apps and need some better monitoring. <a href="http://aldusleaf.org/monitoring-elixir-apps-in-2016-prometheus-and-grafana/">http://aldusleaf.org/monitoring-elixir-apps-in-2016-prometheus-and-grafana/</a></p>]]></content:encoded></item><item><title><![CDATA[Weekly picks 30/09/16]]></title><description><![CDATA[<p>This is the start of my weekly picks. In which I will post everything internet that I see at the internet. Course it is just the most intersting things.</p>

<p>I'm a huge enthusiast of GraphQL concepts but I hadn't had time to play around with it. But I liked this</p>]]></description><link>http://blog.pemedeiros.com/weekly-picks/</link><guid isPermaLink="false">e644975a-d7f5-4341-8cec-95f2991ba24f</guid><dc:creator><![CDATA[Pedro Medeiros]]></dc:creator><pubDate>Sun, 02 Oct 2016 10:03:10 GMT</pubDate><content:encoded><![CDATA[<p>This is the start of my weekly picks. In which I will post everything internet that I see at the internet. Course it is just the most intersting things.</p>

<p>I'm a huge enthusiast of GraphQL concepts but I hadn't had time to play around with it. But I liked this talk that is on speakerdeck and hopefully soon on youtube <br>
<a href="https://speakerdeck.com/benwilson512/no-rest-for-the-wicked">https://speakerdeck.com/benwilson512/no-rest-for-the-wicked</a></p>

<p>Another thing that I've been doing is play more around with golang. This links explaining about the flags has helped me a lot <br>
<a href="http://golang.rakyll.org/go-tool-flags/?utm">http://golang.rakyll.org/go-tool-flags/?utm</a><em>source=golangweekly&amp;utm</em>medium=email</p>

<p>As everybody knows I'm in love with elixir-lang. Elixir lang is the best thing that I saw in the programming world for a long time. I've been following the elixir-core mail list for a long time (guess since the very beginning). And now I have kudos about this discussion. Deprecating the single quotes erlang string for a sigils may facilitate things especially for newcomers <br>
<a href="https://groups.google.com/forum/?utm">https://groups.google.com/forum/?utm</a><em>medium=email&amp;utm</em>source=footer#!msg/elixir-lang-core/_pAjPEayLLI/G66JQEWvBAAJ</p>

<p>Last but not least There's mruby. A not new but still exciting way to put ruby code into embedded or minimal software. I've download, played a little with it and of course I created some small integration with a golang code. I may look better into this in the future. <br>
<a href="http://mruby.org/">http://mruby.org/</a></p>]]></content:encoded></item><item><title><![CDATA[Compile Erlang from Source OSX El Captain]]></title><description><![CDATA[<p>Recently I tried to compile erlang from source on my El Captain. Have done it before a bunch of times, but I wanted to test some new features on their new 19-rc1 release so I downloaded and tried to follow the readme. One thing though that is really mandatory for</p>]]></description><link>http://blog.pemedeiros.com/compile-erlang-from-source-montain-lion/</link><guid isPermaLink="false">0489ce08-2ff2-4b7d-9112-5ff917b611f9</guid><dc:creator><![CDATA[Pedro Medeiros]]></dc:creator><pubDate>Thu, 16 Jun 2016 11:02:05 GMT</pubDate><content:encoded><![CDATA[<p>Recently I tried to compile erlang from source on my El Captain. Have done it before a bunch of times, but I wanted to test some new features on their new 19-rc1 release so I downloaded and tried to follow the readme. One thing though that is really mandatory for me, is the I must compilation with all the apps that erlang ships. Which turned out to be a little headache.</p>

<h3 id="firststepconfigure">First step: configure</h3>

<p>At first we need to configure our environment to check everything that we can do. Luckily Erlang has a nice command line tool that helps we check our environment and set all environment variables before we get started. So after download the source code, just type <code>$ ./otp_build autoconf</code> and we will have a nice set of configuration option to start with.</p>

<p>After that command we will gain a 'configure' command that is the command that will actually check all our dependencies. So just run <code>$ ./configure</code> and wait for it.</p>

<p>At the end of the execution we may have a couple of problems. In my case I have with two libraries, <code>crypto</code> and <code>odbc</code> with erros like <code>ODBC library - link check failed</code>. For crypto to works fine we need to install and link openssl properly. Using brew just makes sure you have the latest version of openssl </p>

<pre><code>$ brew update
</code></pre>

<pre><code>$ brew install openssl
</code></pre>

<p>Then we need to link open ssl. Once we may have some linked files that conflicts with us we need to pass the <code>--force option</code></p>

<pre><code>$ brew link openssl --force
</code></pre>

<p>Crypto must be fine by now. We then need to configure odbc which I found a bit trickier, once it was not a problem in the past. First install <code>unixodbc</code> then some installation paths by using <code>odbc_config</code>.</p>

<pre><code>$ brew install unixodbc
</code></pre>

<pre><code>$ odbc_config --libs
# -L/usr/local/Cellar/unixodbc/2.3.4/lib -lodbc
$ odbc_config --include-prefix
# /usr/local/Cellar/unixodbc/2.3.4/include
</code></pre>

<p>Those two configurations paths we will be using to configure our installation again with the flags <code>CFLAGS</code> and <code>LDFLAGS</code> So just type on the configure phase something similar to this (depending on your output):</p>

<pre><code>$ ./configure CFLAGS="-I/usr/local/include" LDFLAGS="-L/usr/local/lib -lodbc"
</code></pre>

<p>After a coupe of minutes your environment must be ok for the newest erlang version compiled directly from source. So now you just need to continue with the basic <code>make</code> and <code>sudo make install</code>.</p>]]></content:encoded></item><item><title><![CDATA[Elixir Agents]]></title><description><![CDATA[<p>On OTP (Erlang included) we have the concept of a GenServer, that mostly stands for generic server. On Elixir we also have two kind of servers that are not that generic: Agent and Task. Both are implemented using GenServer, but more specific. Agents were created to be a server focused</p>]]></description><link>http://blog.pemedeiros.com/elixir-agents/</link><guid isPermaLink="false">4b6d4a78-0c5d-440a-bbbe-c3d8eef6aa82</guid><dc:creator><![CDATA[Pedro Medeiros]]></dc:creator><pubDate>Tue, 08 Mar 2016 10:00:25 GMT</pubDate><content:encoded><![CDATA[<p>On OTP (Erlang included) we have the concept of a GenServer, that mostly stands for generic server. On Elixir we also have two kind of servers that are not that generic: Agent and Task. Both are implemented using GenServer, but more specific. Agents were created to be a server focused on store data and Task to compute data.</p>

<p>Recently, I've decided to take a better look on Agents and I must admit that I started to like it. I'm use then to play around with some small projects, instead of store data in a full featured DB, it's been a good way to play around.</p>

<h6 id="agent101">Agent 101</h6>

<p>Agent's a simple process that stores and retrieves data given function. For example.</p>

<pre><code class="language-elixir-lang"># Starts an agent proccess with a new MapSet
Agent.start_link(fn -&gt; MapSet.new end, name: :people)  
# {:ok, #PID&lt;0.59.0&gt;}

# Put some data on the Mapset
Agent.update(:people, fn(people_set) -&gt;  
  MapSet.put people_set, %{name: "John Doe"}
end)  
# :ok
Agent.update(:people, fn(people_set) -&gt;  
  MapSet.put people_set, %{name: "Charlie Brown"}
end)  
# :ok
Agent.update(:people, fn(people_set) -&gt;  
  MapSet.put people_set, %{name: "Pedro Medeiros"}
end)  
# :ok

# Recover the data once inserted
Agent.get(:people, fn(people_set) -&gt; people_set end)  
# #MapSet&lt;[%{name: "Charlie Brown"}, %{name: "John Doe"}, %{name: "Pedro Medeiros"}]&gt;
</code></pre>

<p>As we can see we start a process giving it a name (<code>people</code>) and when we need to do any operation on our agent named <code>:people</code>, all we need to do is pass the atom as the first argument, which can also be a PID of the process.</p>

<p>Now that we have the basics of Agents, let's move on creating a new Agent which is unique for our application. let's call this module <code>PeopleStore</code>. Turns out that Module names are atoms on elixir, so we can easily use then as the name of our Agent.</p>

<pre><code class="language-elixir-lang"># people_store.ex
defmodule PeopleStore do  
  def start_link do
    Agent.start_link(fn -&gt; MapSet.new end, name: __MODULE__)
  end
end  
</code></pre>

<p>Now that we have the agent up and running when we run start_link, let's do some operational over it. Notice that we used <code>__MODULE__</code> syntax, which is the equivalent to the model name <code>PeopleStore</code></p>

<pre><code class="language-elixir-lang"># people_store.ex
# ...
  def add_person person do
    __MODULE__
      |&gt; Agent.update(fn people -&gt; 
           MapSet.put people, person
         end)
  end
</code></pre>

<p>Let's say that our users has names that is unique, and we want to retrieve a person based on a name field. We can achieve this by implement our <code>Agent.get/2</code> with <code>Enum.find/2</code></p>

<pre><code class="language-elixir-lang"># people_store.ex
# ...

  def get_person name do
    __MODULE__
      |&gt; Agent.get(fn people -&gt;
           Enum.find people, &amp;(&amp;1.name == name)
         end)
  end
</code></pre>

<p>On Enum.find function we used a shortcut function operator, which is just a syntax sugar for <code>fn x -&gt; x.name == name end</code>. It's visible how it can be simple for small things, it uses <code>&amp;N</code> to determine the argument position of the callback function.</p>

<p>Now with our <code>PeopleStore</code> we can store people and search for people based on name. I'm using it sometimes to fake some test data, It's really useful. And being a GenServer we known It won't have concurrency issues, once an Agent will only do one thing at the time.</p>

<p>Let's See our final Example on using our brand new <code>PeopleStore</code></p>

<pre><code class="language-elixir-lang">AgentStore.start_link #important to instanciate it in memory

AgentStore.add_person(%{name: "john doe"})  
AgentStore.add_person(%{name: "Foo bar"})  
AgentStore.add_person(%{name: "Dave"})

person = Agent.get_person("john doe")

IO.puts("just found #{person.name}")  
# Just found john doe
</code></pre>]]></content:encoded></item><item><title><![CDATA[Chose your tests wisely on elixir]]></title><description><![CDATA[<p>Once a great man said.</p>

<blockquote>
  <p>The game has its ups and downs, but you can never lose <strong>focus</strong> of your individual goals and you can't let yourself be beat because of lack of effort.</p>
  
  <p><em>Michael Jordan</em></p>
</blockquote>

<p>Michael Jordan is nothing more than one of the best players that ever lived.</p>]]></description><link>http://blog.pemedeiros.com/mix-test-the-choice-of-your-test/</link><guid isPermaLink="false">4347b87f-f802-4c83-abdf-58810f09ef8e</guid><category><![CDATA[elixir]]></category><category><![CDATA[test]]></category><dc:creator><![CDATA[Pedro Medeiros]]></dc:creator><pubDate>Sat, 13 Feb 2016 22:27:39 GMT</pubDate><media:content url="http://blog.pemedeiros.com/content/images/2016/02/Best-Software-Development-Strategies-3.png" medium="image"/><content:encoded><![CDATA[<img src="http://blog.pemedeiros.com/content/images/2016/02/Best-Software-Development-Strategies-3.png" alt="Chose your tests wisely on elixir"><p>Once a great man said.</p>

<blockquote>
  <p>The game has its ups and downs, but you can never lose <strong>focus</strong> of your individual goals and you can't let yourself be beat because of lack of effort.</p>
  
  <p><em>Michael Jordan</em></p>
</blockquote>

<p>Michael Jordan is nothing more than one of the best players that ever lived. Based on that focus is also really important for our software. When we build software most of the times we most focus on do one thing right and guaranty that it doesn't fall apart.</p>

<p>That's a trick that can be used with ExUnit to focus on a specific test so we can develop a feature and modify a code without running all the tests (which can take some time depending on the size of your app).</p>

<p>For that <a href="http://elixir-lang.org/docs/master/mix/Mix.Tasks.Test.html">ExUnit</a> comes out of the box with the ability to add tags to your code so it's possible choose what code can be executed. In this case I like to always add the tag <code>:focus</code> on the test that I mos interested on at the moment.</p>

<pre><code class="language-elixir-lang">#...

@tag :focus
test "I say good bye and you say hello" do  
  assert Module.say("good bye") == "hello hello hello"
end  
</code></pre>

<p>This way all I do is run:</p>

<pre><code>mix test --only focus  
</code></pre>

<p>And it's done.. it shows that I have a bunch of tests skipped but only one that passes at the time.</p>

<pre><code>.

Finished in 0.1 seconds (0.1s on load, 0.00s on tests)  
82 tests, 0 failures, 81 skipped  
</code></pre>]]></content:encoded></item><item><title><![CDATA[Ruby 2.3.0 safe operator]]></title><description><![CDATA[<p>Ruby 2.3.0 has been released (yey!) and with it one of the coolest features of all time. The safe operator. </p>

<p>The safe operator is just some simpler way to do something that we already have in rails. But now this feature is in the core language.</p>

<p>Now show</p>]]></description><link>http://blog.pemedeiros.com/ruby-2-3-0-new-features/</link><guid isPermaLink="false">9e0067dc-6d2b-4526-8e20-091b3d1e34c8</guid><dc:creator><![CDATA[Pedro Medeiros]]></dc:creator><pubDate>Fri, 08 Jan 2016 11:53:07 GMT</pubDate><content:encoded><![CDATA[<p>Ruby 2.3.0 has been released (yey!) and with it one of the coolest features of all time. The safe operator. </p>

<p>The safe operator is just some simpler way to do something that we already have in rails. But now this feature is in the core language.</p>

<p>Now show me the code. On rails is pretty common to have errors like this</p>

<pre><code class="language-ruby">&gt; @current_user.trophy.title
# NoMethodError: undefined method `title' for nil:NilClass
</code></pre>

<p>On this little fix solves this problem  </p>

<pre><code class="language-ruby">&gt; @current_user.trophy.try(:title)
# nil
</code></pre>

<p>There's no error raised if one uses the try operator. That's pretty cool. Unfortunately It is limited to the rails stack. Now with the new ruby 2.3.0 is possible to use the safe operator which was attributed to the <code>&amp;</code> key word.</p>

<p>Now the same behaviour we can extend with</p>

<pre><code class="language-ruby">&gt; @current_user.trophy.&amp;title
# nil
</code></pre>

<p>Now is much safer to write code in plain ruby.</p>]]></content:encoded></item><item><title><![CDATA[Rails 4.2 and Refile File upload]]></title><description><![CDATA[<p>When I started working with rails. Rails was on version 2 uploading a file was always kind of a dificult task. There was <a href="https://github.com/thoughtbot/paperclip">paperclip</a> which was pretty neat to work with. It facilitates a lot the way to upload a file into a rails app. Shortly after I met <a href="https://github.com/carrierwaveuploader/carrierwave">carrierwave</a></p>]]></description><link>http://blog.pemedeiros.com/rails-4-2-and-refile-file-upload/</link><guid isPermaLink="false">f50b9847-fc64-4225-ac98-1ec0f646dafc</guid><dc:creator><![CDATA[Pedro Medeiros]]></dc:creator><pubDate>Tue, 28 Apr 2015 16:54:35 GMT</pubDate><content:encoded><![CDATA[<p>When I started working with rails. Rails was on version 2 uploading a file was always kind of a dificult task. There was <a href="https://github.com/thoughtbot/paperclip">paperclip</a> which was pretty neat to work with. It facilitates a lot the way to upload a file into a rails app. Shortly after I met <a href="https://github.com/carrierwaveuploader/carrierwave">carrierwave</a> which I prefered because of the support it had to store multiple images and pre processed files with an Uploader declaration.</p>

<p>New times has come, and wiht it I discovery a new guy that does the same job and has a really nice support for rails 4.2. Meet <a href="https://github.com/refile/refile">refile</a>. Just like paperclip and carrierwave it provides full support to manipulate images, validates types and facilitates data trasnfer with support to cloud servers like amazon s3.</p>

<p>To get started with refile first let's create a scaffold for post and later we will attach an image to the post.</p>

<p><code>bundle exec rails g scaffold post tittle:string content:text image_id:string</code></p>

<p>We added an image attribute with the sufix <code>_id</code>, refile requires that to work. Do not forget that. Then is time to open our model and puts an attachement into it</p>

<pre><code class="language-ruby">class Post &lt; ActiveRecord::BASE  
  attachment :image
end  
</code></pre>

<p>Now we can integrate our upload input into our view with the refile helper to create a upload field at our <code>/views/posts/_form.html.erb</code></p>

<pre><code class="language-ruby">&lt;%= form_for @post do |f| %&gt;  
  &lt;%= f.attachment_field :image %&gt;
&lt;% end %&gt;  
</code></pre>

<p>At our PostsController don't forget the change the permit of strong parameters to validates <code>image</code> and not <code>image_id</code>.</p>

<pre><code class="language-ruby">def post_params  
  params.require(:post).permit(:image) # not :image_id
end  
</code></pre>

<p>Now we are set. We can now create a new post with image and file upload. But now we need to vizualize then. Refile provides a helper for that. just add it to our view.</p>

<pre><code class="language-ruby">&lt;%= image_tag attachment_url(@post, :image, :fill, 150, 150, format: "jpg") %&gt;  
</code></pre>

<p>Yey! now we have our app up and running with the refile gem.</p>]]></content:encoded></item><item><title><![CDATA[MongoDB With Mongoose. Go Schemas!]]></title><description><![CDATA[<p>I've recent started a new nodejs project. I'm a person that likes to experiment a lot. And I heard a lot of buzz around using Mongoose with the MEAN stack. So I've decided to give it a try. I already shipped a project with mongodb using rails and <a href="http://mongoid.org">mongoid</a> and</p>]]></description><link>http://blog.pemedeiros.com/mongoose-and-stuff/</link><guid isPermaLink="false">48873a0d-3ed9-430e-a7ee-7e447cde690f</guid><category><![CDATA[nodejs]]></category><category><![CDATA[mongodb]]></category><category><![CDATA[mongoose]]></category><dc:creator><![CDATA[Pedro Medeiros]]></dc:creator><pubDate>Wed, 10 Dec 2014 16:27:00 GMT</pubDate><media:content url="http://blog.pemedeiros.com/content/images/2014/12/mongodb_logo.png" medium="image"/><content:encoded><![CDATA[<img src="http://blog.pemedeiros.com/content/images/2014/12/mongodb_logo.png" alt="MongoDB With Mongoose. Go Schemas!"><p>I've recent started a new nodejs project. I'm a person that likes to experiment a lot. And I heard a lot of buzz around using Mongoose with the MEAN stack. So I've decided to give it a try. I already shipped a project with mongodb using rails and <a href="http://mongoid.org">mongoid</a> and I loved it. What I loved the most, was the way that mongoid integrates really well with all the rails stack.</p>

<p>Well nodejs is not like rails, while rails is a fullstack framework nodejs is a platform. So some features will be unfair to compare. I also choose to write the code for this new project with <a href="http://coffeescript.org/">coffeescript</a>. Which is a very nice language that compiles to javascript code. So let's get started.</p>

<p>I always create a json file that has all my configurations of my server. So I can easily switch across environments. Using ports, and different styles.</p>

<pre><code class="language-javascript">/* config/config.json */
{
  "development": {
    "mongo": {
      "url": "mongodb://localhost/playapp",
      "options": { 
        "server": { "poolSize": 5 }
      }
    }
  }
  "test": {
    "mongo": {
      "url": "mongodb://localhost/playapptest",
      "options": {
        "server": { "poolSize": 5 }
      }
    }
  }
}
</code></pre>

<p>Now that I have a nice place to store some config files.</p>

<pre><code class="language-coffeescript"># config/db.coffee
path = require 'path'  
mongoose = require 'mongoose'  
config = require path.join(__dirname, 'config')[process.env.NODE_ENV || 'development']

mongoose.connect  config.mongo.url, config.mongo.options

module.exports = mongoose  
</code></pre>

<p>We've got our file set and up for mongoose now is time to use mongoose for his only and one propose. Be a simple Object Document Model or <a href="http://docs.phalconphp.com/en/latest/reference/odm.html">ODM</a>. Which will handle persistence, validations and a schema definition. To illustrate it better let's first write some tests for our app. To write the tests I'm using <a href="http://mochajs.org/">mocha</a>, so let's start.</p>

<pre><code class="language-coffeescript"># spec/models/blogPost_spec.coffee
assert = require 'assert'  
path = require 'path'  
BlogPost = require path.join(__dirname, '../../models/blogPost')

describe 'BlogPost', -&gt;  
  it 'saves the blog post', (done) -&gt;
    blogPost = new BlogPost 
      title: 'My Title',
      content: 'blog post content'
    blogPost.save (err) -&gt;
      assert !err
</code></pre>

<p>What happened there? It's simple, We build a document after the documentation of mongoose and we <a href="http://mongoosejs.com/docs/api.html#model_Model-save">saved it</a>. The save method expect a function which the first parameter is an error if it happens. So we called assert inverting the err message type it returns. If we run our tests it will fail. So it's time to create the code to pass it.</p>

<p>For that mongoose relies on a schema that has to be defined for our model. With this schema we will provide kind of a contract that our model will have to write to our mongo database.</p>

<pre><code class="language-coffeescript"># models/blogPost.coffee
path = require 'path'  
mongoose = require(path.join(__dirname, '../config/db'))

blogPostSchema = mongoose.Schema  
  title: String,
  content: String,
  pubDate: { type: Date, default: Date.now }

BlogPost = mongoose.model 'BlogPost', blogPostSchema  
module.exports = BlogPost  
</code></pre>

<p>Now our model is created, if we run our tests it will pass nicely. This is because we declared the mongoose schema with the content that we needed to save it properly. There's something strange in our schema declaration. We declared a json with <code>title</code> and <code>content</code> fields to be a <code>String</code>. But when I declared pubdate field I didn't pass a type like String, but a object. It is the kind of the flexibility that mongoose give us. If you need to have some operations, such as validations or default value. We can just pass an object with <code>type</code> being the actually type of the field and add what we need to validates, or set default values for our field. More information about the SchemaTypes can be found <a href="http://mongoosejs.com/docs/schematypes.html">here</a> in the documentation.</p>

<p>If we try to a field that is not declared at our schemas when we receive a callback it will not be show at the object that is written at the database. And it will also not be available at our database.</p>

<pre><code class="language-coffeescript">blogPost = new BlogPost  
  title: 'Blog Title'
  content: 'Blog Content'
  foo: 'Bar'

blogPost.save (err, post) -&gt;  
  throw err if err
  # { title: 'Blog Title', content: 'Blog Content'}
  console.log(post) 
</code></pre>

<p>On the example above if we call post.foo we will have undefined. This is a nice feature to have in our System. And is definitely the power of having a Schema mechanism on our hands. But if you got to have the flexibility of mongodb in a field, just need to use the type <code>Schema.Types.Mixed</code>. Within this type you can write anything at that field and mongoose will persist it, even nested objects or arrays.</p>

<h3 id="timetovalidate">Time to validate</h3>

<p>Build schemas for our models in mongodb is a nice feature. But the best part of having a schema is the ability to handle validations. For example, let's say neither our content or title can be blank. To solve this problem with mongoose all we need to do is add an object to the key to the field name and a object with the type of the schema and with the validation option. </p>

<pre><code class="language-coffeescript">blogPostSchema = mongoose.Schema  
  title: { type: String, required: true },
  content: { type: String, required: true },
  pubDate: { type: Date, default: Date.now }
</code></pre>

<p>Just with that required true, mongoose handle the field and does not save the object if the title is not valid for this operations. Returning an error at the save callback function. One can also pass a string instead of true to the required validation. That way when the error is returned it will return the string of your choice. Just be careful to pass the value <code>PATH</code> under brackets <code>{PATH}</code> to indicate the field name.</p>

<pre><code class="language-coffeescript">blogPostSchema = mongoose.Schema  
  title: { type: String, required: '{PATH} is required' },
  content: { type: String, required: required: '{PATH} is required' },
  pubDate: { type: Date, default: Date.now }
</code></pre>

<p>At the <a href="http://mongoosejs.com/docs/validation.html">mongoose docs</a> we can see others handful validations that are nice to use, such as <code>match</code> to restrict via Regex the field that will be saved and the <code>min</code> and <code>max</code> for restrict the range of a number.</p>

<p>To have those buildin validations are great. But the greatest thing is to have custom validations. One can Apply a validation just by declaring an Array in which the first parameter will be function that will handle the validation and the other parameter will be  the text of the error message case this function returns false.</p>

<pre><code class="language-coffeescript">longerThanThree = (val) -&gt;  
  val.length &gt; 3

validatesLongerThanThree = [longerThanThree, '{PATH} is shorter than three']

blogPostSchema = mongoose.Schema  
  title: { type: String, validates: longerThenThree },
  content: { type: String, required: required: '{PATH} is required' },
  pubDate: { type: Date, default: Date.now }
</code></pre>

<p>This is nice way to handle error before acually writing at our database.</p>

<p>And finaly another good thing that I like about mongoose is the ability to create nested schemas. Everyone knows that mongodb has no support for relation between documents the same way that SQL databases does. But It's possible to embed a document inside another. And we can do that with mongoose just declare our nested schema inside another schema. To show it let's first create a Comment schema for our BlogPost.</p>

<pre><code class="language-coffeescript"># models/comment.coffee
path = require 'path'  
mongoose = require(path.join(__dirname, '../config/db'))

CommentSchema = mongoose.Schema  
  content: { type: String, required: true},
  pubDate: { type: Date, default: Date.now }

Comment = mongoose.model 'Comment', CommentSchema  
module.exports = Comment  
</code></pre>

<p>Now all we need to do is to embed this schema inside BlogPost like an array of comments.</p>

<pre><code class="language-coffeescript"># models/blogPost.coffee
path = require 'path'  
Comment = require path.join(__dirname, 'comment')

blogPostSchema = mongoose.Schema  
  title: { type: String, required: true },
  content: { type: String, required: true },
  pubDate: { type: Date, default: Date.now },
  comments: [Comment]

BlogPost = mongoose.model 'BlogPost', blogPostSchema  
module.exports = BlogPost  
</code></pre>

<p>Now we can create a test to see the embedded comment created.</p>

<pre><code class="language-coffeescript"># spec/models/blogPost_spec.coffee
assert = require 'assert'  
path = require 'path'  
BlogPost = require path.join(__dirname, '../../models/blogPost')

describe 'BlogPost', -&gt;  
  it 'saves the blog post', (done) -&gt;
      comments = [
      new Comment(content: 'Foo'),
      new Comment(content: 'Bar')
    ]
    blogPost = new BlogPost 
      title: 'My Title',
      content: 'blog post content'
      comments: comments
    blogPost.save (err, post) -&gt;
      assert post.comments.length == 2
      assert !err
</code></pre>

<p>And if we run our tests it passes!</p>

<p>Mongoose is not the only thing that can handle mongodb operations in node the native <a href="https://www.npmjs.com/package/mongodb">mongo driver</a> is pretty good. But of course it lacks schemas definition, and of course model validations which in my opinion is the killer feature of mongoose.</p>]]></content:encoded></item><item><title><![CDATA[Mix Build tool]]></title><description><![CDATA[<p>One of the best features of elixir language are the tools that ships with it. One of then Is Mix. Mix is build tool that helps create, setup and run an elixir project. To demonstrate how mix do all this, let's create a simple project for a popular Kata named</p>]]></description><link>http://blog.pemedeiros.com/mix-build-tool/</link><guid isPermaLink="false">2990b25c-bfea-4af1-b026-a1267c461978</guid><category><![CDATA[elixir]]></category><category><![CDATA[mix]]></category><dc:creator><![CDATA[Pedro Medeiros]]></dc:creator><pubDate>Mon, 15 Sep 2014 06:36:22 GMT</pubDate><content:encoded><![CDATA[<p>One of the best features of elixir language are the tools that ships with it. One of then Is Mix. Mix is build tool that helps create, setup and run an elixir project. To demonstrate how mix do all this, let's create a simple project for a popular Kata named FizzBuzz.</p>

<p>The rules of FizzBuzz are: <br>
The program must output a line from 1 to a given number with three exceptions:</p>

<ol>
<li>If the value of that line is divided by 3 then the output must be Fizz.  </li>
<li>If the value of that line is divided by 5 then the output must be Buzz.  </li>
<li>If the value of that line is divided by 3 and by 5 the output of that line must be FizzBuzz.</li>
</ol>

<p>Now that we have all the rules. Let's start by creating a new app. The fist step is to type <code>mix new fizz_buzz</code> at the terminal we will see this output:</p>

<pre><code>* creating README.md
* creating .gitignore
* creating mix.exs
* creating config
* creating config/config.exs
* creating lib
* creating lib/fizz_buzz.ex
* creating test
* creating test/test_helper.exs
* creating test/fizz_buzz_test.exs

Your mix project was created successfully.  
You can use mix to compile it, test it, and more:

    cd fizz_buzz
    mix test

Run `mix help` for more commands.  
</code></pre>

<p>Our app is now created, we can now enter at the fizz_buzz folder and see the file structure for a typical elixir app. The three most important files are the <code>mix.exs</code>, <code>test/fizz_buzz_test.exs</code> and <code>lib/fizz_buzz.ex</code>. <code>mix.exs</code> is the file that configures your project. It has 2 main public functions <code>application</code> and <code>project</code>. The <code>project</code> function must return a list with the project information just as the app name, the app version and its dependencies. The <code>application</code> function is where you put the information that will be used to generate an <code>.app</code> file.</p>

<pre><code class="language-elixir"># mix.exs
defmodule FizzBuzz.Mixfile do  
  use Mix.Project

  def project do
    [app: :fizz_buzz,
     version: "0.0.1",
     elixir: "~&gt; 1.1.0-dev",
     deps: deps]
  end

  def application do
    [applications: [:logger]]
  end

  defp deps do
    []
  end
end  
</code></pre>

<p>The <code>lib/fizz_buzz.ex</code> is the file generated that is intended to be the main file of our app. It is created by default and only has an empty module to be implemented. </p>

<pre><code class="language-elixir"># fizz_buzz.ex
defmodule FizzBuzz do  
end  
</code></pre>

<p>The <code>test/fizz_buzz_test.exs</code> file is where you put your tests. In fact every file that lies inside the <code>test</code> will be executed as a test file. By default when we create a project, mix creates a simple test that tests if 1 + 1 is equals 2.</p>

<pre><code class="language-elixir"># fizz_buzz_test.exs
defmodule FizzBuzzTest do  
  use ExUnit.Case

  test "the truth" do
    assert 1 + 1 == 2
  end
end  
</code></pre>

<p>You can run this test with <code>mix test</code> command at the root of the project. We will see that our test will be pass. Try changing the value of the sum from 2 to 3 and see what happens.</p>

<p>Let's start to implement our FizzBuzz by writing some tests. First Let's create a test. Guess the first thing that we got to do is to create the first test from <code>1</code> to <code>3</code> where it will output this:</p>

<pre><code>1  
2  
Fizz  
</code></pre>

<p>And here is the code of the test.</p>

<pre><code class="language-elixir">  test "compute values from 1 to 3" do
    expected_result = """
    1
    2
    Fizz
    """
    assert FizzBuzz.compute(3) == expected_result
  end
</code></pre>

<p>If we try to run the tests again we will see an error. Saying that the function <code>compute/0</code> is not defined. Let's go and implement it.</p>

<pre><code class="language-elixir"># fizz_buzz.ex
defmodule FizzBuzz do  
  def compute(number) do
    """
    1
    2
    Fizz
    """
  end
end  
</code></pre>

<p>Aha! I bet you already realized what I did. In elixir the last expressions is the return value of the function. So what our function does is just returning the expected output for our test. if we run <code>mix test</code> we will see that everything  is passing and we are very happy. This is part of the <a href="http://en.wikipedia.org/wiki/Test-driven_development">TDD philosophy</a>, first we write the test and it should fail, then we write a small piece of software so the test can pass. Then finally we refactor the code. We already known what we want so we can go straight to our code.</p>

<pre><code class="language-elixir">defmodule FizzBuzz do  
  def compute(number) when number &gt; 1 do
    compute(number - 1) &lt;&gt; output_line(number)
  end

  def compute(1) do
    output_line(1)
  end

  defp output_line(number) do
    if rem(number, 3) == 0 do
      "Fizz\n"
    else
      "#{number}\n"
    end
  end
end  
</code></pre>

<p>We can see that at our function <code>compute/1</code> definition we are defining some rules for two specific cases. In Elixir what makes a function signature is its names and its arity (number of  values you can pass to a function). But we can define some rules for a function to execute, just like we did with <code>when</code>. Note that we are using recursion instead of using a conventional loop, it's a <a href="http://elixir-lang.org/getting_started/9.html">common thing at functional languages</a> to use recursion calls. Run <code>mix test</code> and our test pass. Let's write the test to print until 5 so we can see the Buzz word at screen.</p>

<pre><code class="language-elixir">  test "compute values from 1 to 5" do
    expected_result = """
    1
    2
    Fizz
    4
    Buzz
    """
    assert FizzBuzz.compute(5) == expected_result
  end
</code></pre>

<p>If we try to run this test it will fail. This is because we have not implemented a rule of what happens when the number is divided by 5. Since we have refactored our code before, we can just modify our <code>output_line/1</code> function and just add some simple rule there and everything will pass! yey!</p>

<pre><code class="language-elixir">  defp output_line(number) do
    if rem(number, 3) == 0 do
      "Fizz\n"
    else
      if rem(number, 5) == 0 do
        "Buzz\n"
      else
        "#{number}\n"
      end
    end
  end
</code></pre>

<p>Now that everything is passing we can try to refactor that code. I really don't like the inner block thing that we are producing for every new rule we must explicitly create a new if block and close it. Let's try another conditional that is <a href="http://elixir-lang.org/getting_started/5.html#5.3-cond">more clear</a> to use.</p>

<pre><code class="language-elixir">  defp output_line(number) do
    cond do
      rem(number, 3) == 0 -&gt;
        "Fizz\n"
      rem(number, 5) == 0 -&gt;
        "Buzz\n"
      true -&gt;
        "#{number}\n"
    end
  end
</code></pre>

<p>Okay now just one more case we must cover that is if the number is divided by <code>3</code> and <code>5</code> at the same time. First let's write our test case until <code>15</code> run the tests and see it failing.</p>

<pre><code class="language-elixir">  test "compute values from 1 to 15" do
    expected_result = "1\n2\nFizz\n4\nBuzz\nFizz\n7\n8\nFizz\nBuzz\n11\nFizz\n13\n14\nFizzBuzz\n"
    assert FizzBuzz.compute(15) == expected_result
  end
</code></pre>

<p>It fails as expected let's write the last rule first so we can make sure it has a higher precedent.</p>

<pre><code class="language-elixir">  defp output_line(number) do
    cond do
      rem(number, 3) == 0 &amp;&amp; rem(number, 5) == 0 -&gt;
        "FizzBuzz\n"
      rem(number, 3) == 0 -&gt;
        "Fizz\n"
      rem(number, 5) == 0 -&gt;
        "Buzz\n"
      true -&gt;
        "#{number}\n"
    end
  end
</code></pre>

<p>And our tests are passing again. By this time we must already solve the problem. You can try by creating a string that goes from 1 to 100 and will see that our tests will pass. At this point we have our mix application completely  done. We can run test on it. Now let's try to run our code at the console. If we type <code>iex -S mix</code> we will enter at an interactive Elixir console and we will have access to all our code thought here. Let's try by typing <code>FizzBuzz.compute(5)</code>. The output of our FizzBuzz challenge  is done there. And you can try any other value that you want.</p>

<p>This was a quick introduction to mix, a build tool that ships with Elixir. There's a lot to go from here. But having a such nice tool to create a project with a full functional test suite is already great. </p>]]></content:encoded></item><item><title><![CDATA[Elixir - very simple and direct getting started guide]]></title><description><![CDATA[<p><a href="http://www.elixir-lang.com">Elixir</a> is a dynamic, functional language that runs on top of the Erlang VM. It has very friendly syntax and it is meta-programming aware. I've been playing around with Elixir since version 0.5 and for our happiness, this week the version 1.0 of the language was finally released.</p>]]></description><link>http://blog.pemedeiros.com/elixir-very-simple-and-direct-getting-started-guide/</link><guid isPermaLink="false">05133b05-d06b-4dcc-a47e-42c21553fd8e</guid><category><![CDATA[elixir]]></category><dc:creator><![CDATA[Pedro Medeiros]]></dc:creator><pubDate>Sat, 13 Sep 2014 02:53:00 GMT</pubDate><content:encoded><![CDATA[<p><a href="http://www.elixir-lang.com">Elixir</a> is a dynamic, functional language that runs on top of the Erlang VM. It has very friendly syntax and it is meta-programming aware. I've been playing around with Elixir since version 0.5 and for our happiness, this week the version 1.0 of the language was finally released. From the things that I most like about the language I've got to say that the easy tools to build applications in a convenience way is the feature that I like the most. So let's get start and see the basics of running some code and create a simple application.</p>

<p>In the official web site there's a page that show <a href="http://elixir-lang.org/install.html">all the currently possibilities</a> to install elixir in your machine. There are packages for Mac (port, brew), gentoo, arch, fedora and more. I prefer to install with the precompiled packages but for that one must isntall erlang first. <a href="http://elixir-lang.org/install#precompiled-package">Here</a> we can see an easy way to setup our environment to run Erlang and Elixir on our machine. The current version of Elixir requires Erlang 17 or superior. So be sure to install the right version of Erlang first.</p>

<p>Once we setup our environment properly We have four new executables in our environment <code>elixir</code> that can run our elixir code. <code>elixirc</code> to compile the code to a .beam extension to run at the Erlang VM. <code>mix</code> to create and manage our app with the properly steps and dependencies. And lastly <code>iex</code>, and iterative tool to run and evaluate elixir code on the fly. To get start jus type <code>&gt; iex</code> in your terminal and you can start running some code. </p>

<pre><code class="language-elixir">iex &gt; name = "John"  
"John"
iex &gt; "Hello #{name}"  
"Hello John"
</code></pre>

<p>With this code we could start our Hello World. iex evaluate every line of code and output the result for each of then. In this example we can see a string interpolation, a nice feature of elixir. By using <code>#{}</code> we can represent represent any value inside a string without concatenating it explicitly. You can try doing some simple operations in the terminal. such as sum two integer with <code>+</code> or concatenate two strings with <code>&lt;&gt;</code>.</p>

<p>One thing about Elixir and the Erlang VM. Is that there's no mutability. In Erlang if you assign a value to a variable you can't reassign it later. as if you can see bellow, it shows an error if you try to assign the value again. That happens because the <code>=</code> operator is not an assignment operator but a matching operator.</p>

<pre><code class="language-elixir">X = 1.  
1  
X = 2.  
** exception error: no match of right hand side value 2
</code></pre>

<p>At the first time we do <code>X = 1</code> erlang see if X is matched to any value. If it is not matched it will bind <code>1</code> to <code>X</code>. Once <code>X</code> is bind to <code>1</code> if you try to do the match again it will see that <code>1</code> is not <code>2</code> and an error will occur. Elixir is a little bit different from that. Duo the fact that elixir is build on top of the Erlang VM immutability will maintain, but with Elixir it is possible to reassign a value to another variable more than once.</p>

<pre><code class="language-elixir">iex&gt; x = 1  
1  
iex&gt; x = 2  
2  
</code></pre>

<p>One example that we illustrates great the immutability aspect of elixir is how it handles Lists. If we create a list <code>[1,2,3]</code> and than we want to perform an operation at the List, like update a value from it. What Elixir will do is create another list with the new values and return it just like the <a href="http://elixir-lang.org/docs/stable/elixir/List.html#replace_at/3">docs explain</a>. That way we are assigning a new array with the updated values to the variable <code>a</code>.</p>

<pre><code class="language-elixir">iex&gt; a = [1,2,3]  
[1, 2, 3]
iex&gt; a = List.replace_at(a, 1, 10)  
[1, 10, 3]
</code></pre>

<p>With the basics up and ready let's do some code that can be compiled and executed. Basically, Elixir organize everything in modules. The modules contain names functions that can have public or private assessors. Let's write a hello world file names <code>hello.ex</code></p>

<pre><code class="language-elixir"># hello.ex
defmodule HelloWorld do

  def say_hello(name) do
    IO.puts("Hello #{name}")
  end

end

HelloWorld.say_hello("John")  
</code></pre>

<p>Now that we have our file let's run the code. To run this just type on command line <code>elixir hello.ex</code> and you will see the Hello World message popup. But wait, Didn't I said that elixir compiles code to run on Erlang VM. For that we have the command <code>elixirc</code>. If you run <code>elixirc hello.ex</code> it will produce the compiled file <code>Elixir.HelloWorld.beam</code>, which it is just the binary that will load your code into the Erlang VM. Once generated if you enter into <code>iex</code> from that folder you can type <code>HelloWorld.say_hello("Paul")</code> and your code will run. This is because it is already compiled into a .beam file.</p>

<p>This is the quickstart of the language itself. With this basic structure to start to understand  how an Elixir app is build. The next step to go from here is to understand how mix can make our life easy by integrating some tests to our code and by help with dependency management.</p>]]></content:encoded></item><item><title><![CDATA[Authlogic with Rails 4.2]]></title><description><![CDATA[<p>I was doing some rails stuff lately  and needed some authentication module for my application (such as every other application that I ever used). So I was going to use <a href="https://github.com/plataformatec/devise">devise</a> as I always use to bootstrap my authentication module.</p>

<p>But as a unfortunately  surprise. The current version of devise</p>]]></description><link>http://blog.pemedeiros.com/authlogic-with-rails-4-2/</link><guid isPermaLink="false">fe289250-7289-48ad-9447-e1525947ad3d</guid><category><![CDATA[rails]]></category><category><![CDATA[ruby]]></category><category><![CDATA[authentication]]></category><dc:creator><![CDATA[Pedro Medeiros]]></dc:creator><pubDate>Thu, 11 Sep 2014 07:13:57 GMT</pubDate><content:encoded><![CDATA[<p>I was doing some rails stuff lately  and needed some authentication module for my application (such as every other application that I ever used). So I was going to use <a href="https://github.com/plataformatec/devise">devise</a> as I always use to bootstrap my authentication module.</p>

<p>But as a unfortunately  surprise. The current version of devise doesn't work with the new version of rails. So I had to go to other fast alternative. Searching over the web I came across <a href="https://github.com/binarylogic/authlogic">authlogic</a>. I remember that I was using authlogic at my previous job with one specific web, and it worked ok. For my surprise it worked really well with Rails 4.2.0.beta. The only thing that I found confusing was the documentation. It's not as clear as the devise one. But here we go step by step.</p>

<p>First thing I did was put the gem at the gem file.</p>

<pre><code class="language-ruby">gem 'authlogic', '~&gt; 3.4.2'  
</code></pre>

<p>Then we run <code>bundle install</code> to install dependencies and we are ready to create our model. One can create a model with any field that is needed just remember to include some fields that are necessary for authlogic to operate. such as <code>login</code>, <code>email</code>, <code>crypted_password</code>, <code>password_salt</code> and <code>persistence_token</code>. You can choose to have only <code>login</code> or <code>email</code>. But if you have both fields authlogic will lookup for both. This is an example of my model migration.</p>

<pre><code class="language-ruby">class CreateUsers &lt; ActiveRecord::Migration  
  def change
    create_table :users do |t|
      t.string :login
      t.string :name

      t.string :crypted_password
      t.string :password_salt
      t.string :persistence_token

      t.integer :login_count
      t.integer :failed_login_count
      t.datetime :last_request_at
      t.datetime :current_login_at
      t.datetime :last_login_at
      t.string :current_login_ip
      t.string :last_login_ip

      t.timestamps null: false
    end
  end
end  
</code></pre>

<p>Those last fields are from the documentation module <a href="http://rdoc.info/github/binarylogic/authlogic/Authlogic/Session/MagicColumns">MagicColumns</a>. If you have then at your athlogic model they will be used by the library, but you can simply ignore then.</p>

<p>Then is time to tell that your model itself will use authlogic. For that authlogic provides a method named <code>acts_as_authentic</code> which accepts a block of code for configuration. I really had a hard time to find more information about all the possible options it accepts but the one that I really wanted to use was easy to find. That was how to set the crypto provider to use bcrypt.</p>

<pre><code class="language-ruby">class User &lt; ActiveRecord::Base  
  acts_as_authentic do |c|
    c.crypto_provider = Authlogic::CryptoProviders::BCrypt
  end
end  
</code></pre>

<p>Authlogic expect us to create a Session model so it can use it to create and restore our session object for that I just placed over the models folder a class named UserSession that inherits from <code>Authlogic::Session::Base</code></p>

<pre><code class="language-ruby">class UserSession &lt; Authlogic::Session::Base  
end  
</code></pre>

<p>Then It was time to create a controller and a view that would handle the authentication actions. I created then a controller just for that with 3 actions <code>new</code>, <code>create</code> and <code>destroy</code>, just like the rails resource way. and created our form to handle the login properly.</p>

<pre><code class="language-ruby">#routes.rb
resource :user_session, only: [:create, :new, :destroy]  
</code></pre>

<pre><code class="language-ruby">class UserSessionsController &lt; ApplicationController  
  def new
    @user = User.new
  end

  def create
    @user_session = UserSession.new params.require(:user)
      .permit(:login, :password)
    if @user_session.save
      redirect_to root_path
    else
      redirect_to new_user_session_path
    end
  end

  def destroy
    current_user_session.destroy
    redirect_to new_user_session_path
  end
end  
</code></pre>

<pre><code class="language-ruby">&lt;!-- app/views/user_sessions/new.html.erb --&gt;  
&lt;%= form_for @user, url: user_session_path, method: :post, html: { class: 'form-horizontal', role: 'form' } do |f| %&gt;  
  &lt;div class='form-group'&gt;
    &lt;%= f.text_field :login, class: 'form-control', placeholder: 'Login' %&gt;
  &lt;/div&gt;
  &lt;div class='form-group'&gt;
    &lt;%= f.password_field :password, class: 'form-control', placeholder: 'Password' %&gt;
  &lt;/div&gt;
  &lt;%= f.submit 'Login', class: 'btn btn-primary' %&gt;
  &lt;% end %&gt;
&lt;% end %&gt;  
</code></pre>

<p>Now is time to create our helper methods at the controller so we can access it across our application. For that I just follow what Ryan Bates did on that <a href="http://railscasts.com/episodes/160-authlogic">outdated (but f##### useful) railscasts)</a>.</p>

<pre><code class="language-ruby">class ApplicationController &lt; ActionController::Base  
  self.responder = ApplicationResponder
  helper_method :current_user_session, :current_user

# ...

private  
  def current_user_session
    @current_user_session ||= UserSession.find
  end

  def current_user
    @current_user ||= current_user_session &amp;&amp; current_user_session.user
  end
end  
</code></pre>

<p>We can place that helper method in any part of our app to verify if the user is logged in. and to permit access to certain actions.</p>

<h3 id="conclusion">Conclusion</h3>

<p>It was not hard at all to setup authlogic I can happily use it during all my app development. But to tell the truth I can't wait to go back to devise just for the good documentation and examples. That is the thing that authlogic lacks the most. But it is an good and easy library to setup.</p>]]></content:encoded></item><item><title><![CDATA[Back to C++]]></title><description><![CDATA[<p>Recently I’m just starting to relearning c++ so I can do dig in some legacy code at the company I work for. And for that I decided to start with the basics step by step and take on some notes about all the process of relearning it. </p>

<p>I’m</p>]]></description><link>http://blog.pemedeiros.com/back-to-c/</link><guid isPermaLink="false">92b4e3c7-6e38-4ef4-acc2-d3fc356c3844</guid><dc:creator><![CDATA[Pedro Medeiros]]></dc:creator><pubDate>Sun, 07 Sep 2014 02:26:06 GMT</pubDate><content:encoded><![CDATA[<p>Recently I’m just starting to relearning c++ so I can do dig in some legacy code at the company I work for. And for that I decided to start with the basics step by step and take on some notes about all the process of relearning it. </p>

<p>I’m a native C++ programmer. What that means is that C++ is my first programming language that I learned for good, and was by coding c++ that I’ve learned to love to programing and is the thing that I do everyday, doesn’t matter if it is for my day job work, I’m always writing some piece of code for whatever reasons. Unfortunately, C++ was not so good to supply my old necessities anymore like it used to. I wanted to get the job done fast and to complete my goals as fast as I can with an elegant code. That was when I learned Java, a.k.a The biggest mistake of my life. Java has a error proof way that is nice for some people that are already into C++, but it was not I was really looking for. It seems that It took a lot of the verbose of C++, simplified a little with not a worth gain. It was when I met ruby, javascript, node, python and programming friendly languages like that.</p>

<p>Those kind of scripting languages were a game changer for me. I could do what I wanted as fast as I could and with such expressiveness that I could not find either in C++ or in Java. So I left C++ behind for sometimes. I really wish I could left Java behind too, but I always had to code something or another in Java because the IT world, specially in Brazil, basically breaths Java. </p>

<p>During the time I was looking for expressiveness and fast development, I ended up going away from some system development and away from some root concepts that I was missing somehow. So In the last years I ended up reading some articles about programming in C++ again and I was looking for what was new in other languages, like Scala, Go, Rust. I had to say. I really liked what Rust and Go are promising. But I just can’t introduce any of those languages to the table of the companies that are not wiling to try new things just yet. So I have to dig in deeper on what they are using and propose some changes based on what they are actually doing. So I’m relearning to fly on C++ code.</p>

<p>I bet that the hardest thing is going to be how to make a 100% portable code. I never was a biggest windows fan. All my development stack are based on *nix systems. But one thing that I learned is that C++ is widely used on Windows development. Here where I live mostly of the people that are programming on C++ are using Windows for development. That scares me a little, but that’s just how it is. I did not decided yet how I’m going to do that. But I’m starting by reading some basic C++ concepts and hopeful I’m gonna keep updating my status on that.</p>

<p>And of course I’m planning on write some more on c++ development. </p>]]></content:encoded></item><item><title><![CDATA[Promises on Javascript]]></title><description><![CDATA[<p>If you are programming javascript in a while. Or just started nodejs and are having some trouble with the famous callbacks hell that javascript provides. Well that's the price to use a lot a asynchronous functions. just like the code below</p>

<pre><code class="language-javascript">database.getUserProfile(function(profile, err){  
  if(!err){
    networkAdapter.getTwitterInfo(</code></pre>]]></description><link>http://blog.pemedeiros.com/promises-on-javascript/</link><guid isPermaLink="false">22714676-30bc-4359-b889-274e8a40d8ac</guid><category><![CDATA[javascript]]></category><category><![CDATA[promise]]></category><dc:creator><![CDATA[Pedro Medeiros]]></dc:creator><pubDate>Tue, 22 Jul 2014 07:22:41 GMT</pubDate><content:encoded><![CDATA[<p>If you are programming javascript in a while. Or just started nodejs and are having some trouble with the famous callbacks hell that javascript provides. Well that's the price to use a lot a asynchronous functions. just like the code below</p>

<pre><code class="language-javascript">database.getUserProfile(function(profile, err){  
  if(!err){
    networkAdapter.getTwitterInfo(profile.twitterUrl, function(twitterData, err){
      if (!err){
        database.getFriendsFromTwitter(twitterData, function(friends, err){
          if(!err) {
            var friendsOnTwitter = friends.map(function(friend){
              return friend.userName;
            });
            sendResponse(friendsOnTwitter);
          }
        });
      }
    });
  }
});
</code></pre>

<p>There are up to 6 levels of indentation on that code. and it can potentially grown. This is because we are just doing 2 database calls and 1 network call that has to be treated in a synchronous way. That is something that sucks about javascript callbacks. Sure the code is not perfectly planned. But It's just an example of how it could have grown wrong doing just something that any system nowadays has to do. Which is handle multiple IO calls. For that problems like that Promises were created.</p>

<p>For an example of how handle promises I'm gonna use the <a href="https://github.com/kriskowal/q">Q library</a> which is maintained currently by <a href="https://github.com/kriskowal">Kris Kowal</a>. This library is highly used at many places that has a javascript interpreter, like nodejs and all the major web browsers.</p>

<p>To use the example above with it our code will became really more clear.</p>

<pre><code class="language-javascript">database.getUserProfile()  
  .then(function(profile){
    return networkAdapter.getTwitterInfo(profile.twitterUrl);
  }).then(function(twitterData){
    return database.getFriendsFromTwitter(twitterData)
  }).then(function(friends){
    var friendsOnTwitter = friends.map(function(friend){
      return friend.userName;
    });
    sendResponse(friendsOnTwitter);
  });
</code></pre>

<p>Just like that our code became so much more readable. With the then statement we pass a callback that will eventually be called if our expression executes successfully, in this case the IO calls. And we chain all the callbacks by returning a new promises that will perform another IO call that will call the next then callback in the stack.</p>

<p>But wait, what about the error handles. What happened to them?</p>

<p>They can be easily replace with just one last call at the end of the stack of promises handles, which is the catch call.</p>

<pre><code class="language-javascript">database.getUserProfile()  
  .then(function(profile){
    return networkAdapter.getTwitterInfo(profile.twitterUrl);
  }).then(function(twitterData){
    return database.getFriendsFromTwitter(twitterData)
  }).then(function(friends){
    var friendsOnTwitter = friends.map(function(friend){
      return friend.userName;
    });
    sendResponse(friendsOnTwitter);
  }).catch(function(err){
    console.log(err);
  });
</code></pre>

<p>Even the error handles became more clear to read, just like that. That's why I believe that the use of a Promise library can have a really good use. Especially now that the next itteration of the javascript standart will support Promises natively (<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise</a>)</p>

<p>References:</p>

<p>Promisses/A spec <a href="http://wiki.commonjs.org/wiki/Promises/A">http://wiki.commonjs.org/wiki/Promises/A</a> <br>
ES6 own implementation of promisses <a href="http://www.html5rocks.com/en/tutorials/es6/promises/">http://www.html5rocks.com/en/tutorials/es6/promises/</a></p>]]></content:encoded></item><item><title><![CDATA[The utility of HTTP GET method]]></title><description><![CDATA[<p>Working with the web for a considerable time. I've came across the following though: "You don't do an GET anymore. I'ts 'Ugly' to do so because it generates an ugly URL". That came especially from some juniors devs that I've contacted in recent years.</p>

<p>But to tell the true. It</p>]]></description><link>http://blog.pemedeiros.com/the-utility-of-http-get-method/</link><guid isPermaLink="false">97de0ba3-bb29-4d6f-9d8b-a70ff5d7084e</guid><dc:creator><![CDATA[Pedro Medeiros]]></dc:creator><pubDate>Fri, 25 Apr 2014 17:01:55 GMT</pubDate><content:encoded><![CDATA[<p>Working with the web for a considerable time. I've came across the following though: "You don't do an GET anymore. I'ts 'Ugly' to do so because it generates an ugly URL". That came especially from some juniors devs that I've contacted in recent years.</p>

<p>But to tell the true. It is a little bit of ugly to pass a lot of parameters vi the get attribute to url. But it has a good and meaningful propose. It is made to... wait for it... to <em>get</em> the data from somewhere. </p>

<p>As it is pointed by some authors in the REST/Hypermedia/Webservice literature. When you perform the an HTTP request using the GET parameter at the header. You must not interfere with the universe that the service you are fetching the data from lives in. That's why when you enter some news sites you are fetching the content with it.</p>

<p>The Get method must be safe. And of course it must also be idempotent. Which means it must not cause any side effects to the system. It only exists to fetch the data by a meaning url. For example the url <code>/books</code> says something. It says that it will fetch some books. But let's says I'm developing some library system. And of course I need to apply some filters to the <code>/books</code> url. In that case It's really ok to pass parameters at the url like <code>/books?genre=fiction</code>. It has a meaning that I want to fetch some books of my system And wanna to apply the filter that says, I wanna books with the genre fiction. It's not so ugly like the guy I quoted at the beginning of my post, because it has some meaning. </p>

<p>But let's say That I wanna to fetch the cover of a specific book. In that case you should use the cover parameter in the URL and not in the segment expansion. Which means that your url can be <code>/books/13/cover</code>. That means that I will fetch the <em>cover</em> of the <em>book</em> with the id <em>13</em>. The expansion path must be used to represent some kind of segment of the resource. In that case. the cover of an specific book.</p>]]></content:encoded></item></channel></rss>