<?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 Nassredean Nasseri on Medium]]></title>
        <description><![CDATA[Stories by Nassredean Nasseri on Medium]]></description>
        <link>https://medium.com/@nassredean?source=rss-72f0167b79d0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*QW_WnObml7C2ZjMevtOEiw.png</url>
            <title>Stories by Nassredean Nasseri on Medium</title>
            <link>https://medium.com/@nassredean?source=rss-72f0167b79d0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 14:00:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nassredean/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[Introducing Fir, the Friendly, Interactive Ruby REPL]]></title>
            <link>https://medium.com/building-vts/introducing-fir-the-friendly-interactive-ruby-repl-527e41a011db?source=rss-72f0167b79d0------2</link>
            <guid isPermaLink="false">https://medium.com/p/527e41a011db</guid>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Nassredean Nasseri]]></dc:creator>
            <pubDate>Tue, 23 Jan 2018 22:19:57 GMT</pubDate>
            <atom:updated>2018-01-23T22:48:56.248Z</atom:updated>
            <content:encoded><![CDATA[<p>I haven’t been posting here much because most of my free time has been spent working on a Ruby REPL that I call <a href="https://github.com/dnasseri/fir">Fir</a>, which stands for friendly-interactive-Ruby. The Ruby community has no shortage of great REPL’s — the default irb is pretty good, and <a href="https://github.com/pry/pry">pry</a> offers a fantastic REPL as well as an interactive debugger that really highlights some of the great features of the Ruby language. In my daily work, I also really enjoy some of the autosuggestion features that the <a href="https://github.com/fish-shell/fish-shell">fish</a> shell offers, so much so that I got to thinking about integrating those features into a Ruby REPL. If you’re not familiar with the fish shell, this is what some of those features look like in action:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*D4phZGG4AS89AP4ri3cujA.gif" /><figcaption>the fish shell offers terrific autosuggestion</figcaption></figure><p>As you can see, fish offers as you type autocompletion based on your history, programs in your path, and directories on your machine. It’s really quite clever, and anytime I’m using another shell, I tend to miss it. Fir does something similar, by suggesting lines from your .irb_history file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*8vD1JjzFfy0MxBctc3zMzQ.gif" /><figcaption>Fir’s autocompletion in action.</figcaption></figure><p>Fir not only offers suggestions as you type, it also indents and dedents code as you type it. Take a look at how it handles this begin/rescue block:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*l8QmRv1r1Uz2-pWfOAzQ0g.gif" /></figure><p>As you can see, Fir is smart enough to dedent the rescue keyword as soon as you type it. The difference between Fir and a REPL like pry (or most others) is that Fir parses the syntax and re-renders the screen every time it receives a key input, as opposed to only when the program receives select inputs like tab or enter. Since every keystroke triggers a loop and a full re-render, we can continuously update the screen with new indents, suggestions, and in the future, colorization. Like other REPLs, Fir only triggers a full evaluation of the inputted code when it forms a self contained executable block, and the user presses enter.</p><h4>Implementing as you type updates with raw input</h4><p>In order to achieve the functionality described above inside our command line programs, we need to leverage “raw” terminal drivers. Terminals and REPLs usually use “cooked”, or canonical, input. With cooked input characters are buffered internally until a carriage return is inputted to the program, at which point the line is processed. Cooked functionality is actually what allows for certain characters to be treated as special, e.g. control sequences or backspace. It is on this system that programs usually base their line editing. If instead we want to manually handle characters as the program receives them, and also prevent them from being echoed to the screen, than we need to force the terminal to use a raw driver. In Ruby we can force stdin or stdout into raw mode as follows:</p><pre>while true<br>  $stdin.raw do |raw_input|<br>    raw_input.getc<br>  end<br>end</pre><p>If you run the above program and start typing, <strong>you will see nothing happens on the screen</strong>, and thats good! The program is fetching the raw characters, and preventing their default behavior, which in this case, is rendering them to the screen. This is essentially what Fir is based on, fetching raw input, processing it, and then manually drawing to the screen using <a href="https://en.wikipedia.org/wiki/ANSI_escape_code">ANSI escape sequences</a> to do things like erase or move the cursor. It also means that we can handle the characters as we receive them, instead of waiting for a carriage return.</p><p>Now as I mentioned before, you may have noticed that trying to ctrl-d or exit the program using the standard process control characters did not work. Sorry about that! You see one of the downsides of raw terminal drivers is that you have to manually handle <em>everything</em>. In this case, those standard process control characters are doing nothing to end the program, so you are going to have to send that runaway Ruby process a kill signal ;).</p><h4>Capturing escape keys</h4><p>Certain keys, such as the arrow keys, are prefixed by an “escape” sequence. These escape characters are actually not characters at all, but strings that begin with the escape character “\e”. For instance, the left arrow character is represented by “\e[D”. Let’s modify our raw input example to inspect and display the character we have trapped, and see what a left arrow key looks like.</p><pre>while true<br>  $stdin.raw do |raw_input|<br>    $stdin.puts “CHARACTER:”: raw_input.getc.inspect<br>  end<br>end</pre><p>Run the program and then hit the left arrow key, and you should see something like this:</p><pre>$ ruby raw_mode_example.rb <br>CHARACTER: “\e”<br> CHARACTER: “[“<br> CHARACTER: “D”</pre><p>What happened here? Well if we read the <a href="http://ruby-doc.org/core-2.3.0/IO.html#method-i-getc">documentation for getc </a>we see that getc “Reads a one-character string from ios”, and this is not a one character string! This posed a substantial challenge for Fir, since the left arrow was broken down into its component characters, my program behaved as if the user had just hit escape, and then left bracket, and then d. Not what we want.</p><p>I stumbled into a solution <a href="http://www.alecjacobson.com/weblog/?p=75">here</a>. The solution is to spawn an additional thread when the program detects an escape key where we call getc on the input twice, and then kill the thread very quickly. If the the escape was the beginning of the long character sequence, as in the case of left arrow, we are able to trap it, and if not the thread is killed and the program isn’t blocked waiting for more input. Here’s what that solution looks like inside the F<a href="https://github.com/dnasseri/fir/blob/master/lib/fir/key.rb">ir key class</a>.</p><pre>input.raw do |raw_input|<br>  key = raw_input.sysread(1).chr<br>  if key == “\e”<br>    skt = Thread.new { 2.times { key += raw_input.sysread(1).chr } }<br>    skt.join(0.0001)<br>    skt.kill<br>  end<br>  key<br>end</pre><h4>Conclusion</h4><p>All in all, this has been a really fun project for me to pursue, and I have learned a ton. I am looking for any contributions, so if you would like to contribute, o<a href="https://github.com/dnasseri/fir">pen a pull request, and submit a PR</a>!</p><p>This blog post was originally published on my blog here: <a href="https://www.nasseri.io/">https://www.nasseri.io/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=527e41a011db" width="1" height="1" alt=""><hr><p><a href="https://medium.com/building-vts/introducing-fir-the-friendly-interactive-ruby-repl-527e41a011db">Introducing Fir, the Friendly, Interactive Ruby REPL</a> was originally published in <a href="https://medium.com/building-vts">Building VTS</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Structure and Interpretation of Ruby Programs]]></title>
            <link>https://medium.com/building-vts/the-structure-and-interpretation-of-ruby-programs-362db0412f29?source=rss-72f0167b79d0------2</link>
            <guid isPermaLink="false">https://medium.com/p/362db0412f29</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ruby]]></category>
            <dc:creator><![CDATA[Nassredean Nasseri]]></dc:creator>
            <pubDate>Sun, 05 Nov 2017 16:08:08 GMT</pubDate>
            <atom:updated>2017-11-06T18:48:54.894Z</atom:updated>
            <content:encoded><![CDATA[<p>Whenever a ruby program is run, the program is first lexed into tokens, then the tokens are assembled into an abstract syntax tree, and finally the AST is compiled into virtual machine instructions. In this post, we will explore each of these steps in detail.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*n8UYTZHJ3kFFMPB-kkzkcA.png" /></figure><p>First, an example program</p><pre>class Math<br>  def add(x, y)<br>    x + y<br>  end<br>end     <br><br>Math.new.add(1, 2)</pre><p>Whenever you run a ruby program, ruby steps through the characters in the program one at a time and groups them into special words called “tokens”. These tokens are not guaranteed to be valid Ruby. At this point the stream of tokens could be invalid. It is the responsibility of the parser to determine whether the inputted program is valid or not.</p><p>We can actually see how Ruby’s tokenization would treat this program using the built in tool ‘ripper’. Lets take a look at how the definition of the add method is tokenized using the following code:</p><pre>require &#39;ripper&#39;<br>require &#39;pp&#39;<br><br>code = &lt;&lt;CODE<br>def add(x, y)<br>  x + y<br>end<br>CODE<br><br>pp Ripper.lex(code)</pre><p>This results in the following output:</p><pre>[[[1, 0], :on_kw, &quot;def&quot;],<br> [[1, 3], :on_sp, &quot; &quot;],<br> [[1, 4], :on_ident, &quot;add&quot;],<br> [[1, 7], :on_lparen, &quot;(&quot;],<br> [[1, 8], :on_ident, &quot;x&quot;],<br> [[1, 9], :on_comma, &quot;,&quot;],<br> [[1, 10], :on_sp, &quot; &quot;],<br> [[1, 11], :on_ident, &quot;y&quot;],<br> [[1, 12], :on_rparen, &quot;)&quot;],<br> [[1, 13], :on_ignored_nl, &quot;\n&quot;],<br> [[2, 0], :on_sp, &quot;  &quot;],<br> [[2, 2], :on_ident, &quot;x&quot;],<br> [[2, 3], :on_sp, &quot; &quot;],<br> [[2, 4], :on_op, &quot;+&quot;],<br> [[2, 5], :on_sp, &quot; &quot;],<br> [[2, 6], :on_ident, &quot;y&quot;],<br> [[2, 7], :on_nl, &quot;\n&quot;],<br> [[3, 0], :on_kw, &quot;end&quot;],<br> [[3, 3], :on_nl, &quot;\n&quot;]]</pre><p>Each nested array in above output represents a single token. The structure of the array is as follows:</p><pre>[[line number, text column], token name, characters]</pre><p>The token name symbols in the output map to token types defined inside of the file “parse.y” of the ruby source code. Though the symbol names are not one to one with the C definition inside parse.y, the output of ripper captures what Ruby does internally as it encounters tokens. For instance “def” is mapped to :on_kw indicating that it is ruby keyword. Similarly “end” is also mapped to :on_kw. However inside of ruby “def” would be treated as the token of type “keyword_def”, and “end” would be treated as the token of type “keyword_end”. There are some other differences in the output of ripper and the internal representation of each token, but ripper gives us a good idea of how ruby tokenization works. It is important to remember that tokenization happens in a character by character streaming fashion. This gif should help visualize how a stream of characters is turned into a stream of tokens:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fg5jUEKv1pSCkuAxmEVvww.gif" /><figcaption>Ruby tokenization in action</figcaption></figure><h4>Parsing</h4><p>After ruby has finished converting the text of the program into a stream of tokens, the tokens are then grouped into logical units that ruby can understand. This is the parsing step, and it is at this step that the program is determined to be valid ruby or not. Ruby does this by determining if the stream of tokens conform the grammar rules defined in the parse.y file. If so, the stream of tokens are converted into a corresponding abstract syntax tree. The AST is a data structure representation of the syntactical meaning of your ruby program. The handy ripper tool can again help us visualize what this AST looks like to ruby, this time using the “sexp” function:</p><pre>require &#39;ripper&#39;<br>require &#39;pp&#39;</pre><pre>code = &lt;&lt;CODE<br>def add(x, y)<br>  x + y<br>end<br>CODE</pre><pre>pp Ripper.sexp(code)</pre><p>Output:</p><pre>[:program,<br> [[:def,<br>   [:@ident, &quot;add&quot;, [1, 4]],<br>   [:paren,<br>    [:params,<br>     [[:@ident, &quot;x&quot;, [1, 8]], [:@ident, &quot;y&quot;, [1, 11]]],<br>     nil,<br>     nil,<br>     nil,<br>     nil,<br>     nil,<br>     nil]],<br>   [:bodystmt,<br>    [[:binary,<br>      [:var_ref, [:@ident, &quot;x&quot;, [2, 2]]],<br>      :+,<br>      [:var_ref, [:@ident, &quot;y&quot;, [2, 6]]]]],<br>    nil,<br>    nil,<br>    nil]]]]</pre><p>This output is a bit terse, so I’ve included a visual reprsenation of the AST below. Each node in the tree represents a construct in the program. For instance, the addition of the identifier’s x and y is represented by a “binary” node. A binary node encodes an operation that performs on two elements of a set to derive a third element.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*t_Gxd--I2ZBlrTDSj4InRA.png" /><figcaption>The structure of the AST</figcaption></figure><p>The generated AST encapsulates everything ruby needs to understand your program, and with that, ruby can move on to the third and final step.</p><h4>Compilation</h4><p>Ruby is a compiled language in much the same way that Java is. While ruby is not compiled down to native machine code, it is compiled into a set of bytecode instructions that are interpreted by a virtual machine. In the case of Java the VM is JVM, in the case of Ruby it is YARV, which stands for “Yet another ruby virtual-machine”.</p><p>In order to compile your program, ruby recursively iterates over the nodes in the AST from the top down and compiles each node into corresponding YARV instructions. Once more, we can use built in tools to examine how ruby compiles our AST into YARV instructions.</p><pre>code = &lt;&lt;CODE<br>def add(x, y)<br>  x + y<br>end<br>CODE</pre><pre>puts RubyVM::InstructionSequence.compile(code).disasm</pre><p>Output:</p><pre>== disasm: #@&gt;================================<br>0000 trace            1                                               (   1)<br>0002 putspecialobject 1<br>0004 putobject        :add<br>0006 putiseq          add<br>0008 opt_send_without_block , <br>0011 leave<br>== disasm: #&gt;=======================================<br>local table (size: 2, argc: 2 [opts: 0, rest: -1, post: 0, block: -1, kw: -1@-1, kwrest: -1])<br>[ 2] x     [ 1] y<br>0000 trace            8                                               (   1)<br>0002 trace            1                                               (   2)<br>0004 getlocal_OP__WC__0 4<br>0006 getlocal_OP__WC__0 3<br>0008 opt_plus         , <br>0011 trace            16                                              (   3)<br>0013 leave                                                            (   2)</pre><p>YARV is a stack oriented virtual machine, so most of the instructions invlove putting an object onto the stack, and then executing an operation against the values on the stack. The top block of instructions are used to define the “add” method. Essentially the instructions put the method name on the stack, and then calls “define_method” a C function that is used by YARV to create a new ruby method. In the second block, a local table is defined which represent the arguments our function can accept.</p><h4>Conclusion</h4><p>In this post we explored how ruby translates the text of a program, first into tokens, then into a structure called an AST, and finally into intstructions usable by the virtual machine. These three passes are what allow ruby to be interpreted by the virtual machine. Hopefully after reading this post you will have a little bit better understanding about what exactly happens when you boot up a ruby process.</p><p>This blog post was originally published on my blog here: <a href="https://www.nasseri.io/">https://www.nasseri.io/</a></p><p>The company I work for, VTS, is always on the lookout for talented people who want to be a part of what we’re building. You can find out more about us, and see all our open roles, on our <a href="https://www.vts.com/careers">careers page</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=362db0412f29" width="1" height="1" alt=""><hr><p><a href="https://medium.com/building-vts/the-structure-and-interpretation-of-ruby-programs-362db0412f29">The Structure and Interpretation of Ruby Programs</a> was originally published in <a href="https://medium.com/building-vts">Building VTS</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Postgres Window Functions]]></title>
            <link>https://medium.com/building-vts/understanding-postgres-window-functions-697bc0ff2ed4?source=rss-72f0167b79d0------2</link>
            <guid isPermaLink="false">https://medium.com/p/697bc0ff2ed4</guid>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Nassredean Nasseri]]></dc:creator>
            <pubDate>Thu, 02 Jun 2016 19:48:25 GMT</pubDate>
            <atom:updated>2016-06-02T19:48:25.285Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently I stumbled into a very handy feature of Postgres — window functions. A window function gives you a “window” into other rows which are somehow related to the current row. You can then preform a calculation across that set of rows. Window functions behave much like regular aggregate functions, with the caveat that the rows do not become grouped into a single row! Let’s explore this feature, and why it might be useful.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/587/1*CMi58cQ9I-WfSM9r1yPedA.png" /><figcaption>Imagine the painting is the current row. The window is… the window. It is related to the scene depicted in the painting, and provides it the surrounding context.</figcaption></figure><p>Imagine we have an application which serves to record sales data for different stores. The applications database has three tables: sales, users, and stores.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a0d04b7f6b38b550d952e410e7cc8628/href">https://medium.com/media/a0d04b7f6b38b550d952e410e7cc8628/href</a></iframe><p>In our application, users enter sales data for a given store. The sales table has a column for “entered_at” which represents when the sales data was entered.</p><h4>Using Windows Functions with Aggregate Functions</h4><p>Lets say we wanted to aggregate the sales for each store. We could do this easily using a GROUP BY statement.</p><pre>SELECT store_id, sum(amount) as amt FROM sales GROUP BY sales.store_id</pre><p>which yields the following rows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d825b34ba03fcd4f5052ff59bccd1f74/href">https://medium.com/media/d825b34ba03fcd4f5052ff59bccd1f74/href</a></iframe><p>But what if we wanted to return each row from the sales table individually, with the corresponding stores total sales amount. We can do this using a window function.</p><pre>SELECT store_id, sum(amount) OVER (PARTITION BY store_id) FROM sales</pre><p>which results in:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/941ff74b868564682306047248397ef8/href">https://medium.com/media/941ff74b868564682306047248397ef8/href</a></iframe><p>Let’s break this down a bit. The store_id column is self explanatory. The sum aggregates the amount from every row that has the same store_id as the current row. The OVER keyword is what causes the aggregate function to be treated as a window function, and compute the aggregate across the rows in the window without grouping.</p><p>But how do we define the window? How does Postgres know which subset of rows we want to aggregate? The answer lies in the PARTITION keyword. The partition is what divides the table rows into distinct window frames. In this case we partition the table by the store_id.</p><p>One thing to note is that we can use an aggregate function as a window function. We could have just as easily written</p><pre>SELECT store_id, COUNT(*) OVER (PARTITION BY store_id) FROM sales</pre><h4>Using the Rank Function</h4><p>Postgres provides a number of window specific functions which you can find <a href="https://www.postgresql.org/docs/9.3/static/functions-window.html">here</a>. One of the most common use cases for window functions is to rank a window of rows using the rank function.</p><p>Lets say we wanted to rank each sales record by the amount entered for a given store_id. We can do this easily with the rank function:</p><pre>SELECT store_id, amount, rank() OVER (PARTITION BY store_id ORDER BY amount DESC) AS amount_rank FROM sales</pre><p>The resulting table would look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1d45bd5e24774cd1a43ae9397418e7a1/href">https://medium.com/media/1d45bd5e24774cd1a43ae9397418e7a1/href</a></iframe><p>You may notice that if a two or more rows have the same amount, they receive the same rank. The rank function will assign a unique number to each distinct row, but it leaves a gap when there are multiple rows with the same rank. Take a look at the rows with a store_id of 1. We can see that there are two ranks of 2, so the next rank is incremented not to 3, but to 4. the dense_rank function does not do this and instead the row with a rank of 4 would have a rank of 3.</p><p>These have been some pretty simple examples of window functions. Let’s move onto something a little bit more interesting.</p><h4>Complex Window Partitions</h4><p>Let’s say that in our application we want to be able to get the most recent sales data entered for a given month/year combination and a given store. This problem can be solved handily using window functions.</p><p>Let’s start by crafting a query to give us the store_id, the month of the entered date, the year of the entered_date, and the amount of the sale.</p><pre>SELECT store_id, EXTRACT(month from entered_at) as mm, EXTRACT(year from entered_at) as yyyy, amount FROM sales</pre><p>Which yields:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/61456164040b62499fea3a155c7e85cb/href">https://medium.com/media/61456164040b62499fea3a155c7e85cb/href</a></iframe><p>Note that we are using the EXTRACT function which allows us to retrieve subfields such as year, hour, day, month from date/time values.</p><p>The next thing we want to do is to partition the table. The original intent of our query was to grab the most recent sales data entered for a given month/year combination and a given store. So our partition should be defined as follows “for each row, get me the rows with the same month/year in the entered date, and the same store_id”. In other words, we need to partition by the extracted month, year, and store_id.</p><p>Now here’s the problem. Unlike a GROUP BY statement, we can’t partition over several columns. So how can we get the window frames we want?</p><p>The solution I found was to use the string function concat, and grouping by the concatenated value of the extracted month/year, and the store_id.</p><pre>SELECT store_id, EXTRACT(month from entered_at) as mm, EXTRACT(year from entered_at) as yyyy, amount, rank() OVER (PARTITION BY concat(extract(month from entered_at), extract(year from entered_at), store_id) ORDER BY entered_at DESC) AS entered_at_rank FROM sales ORDER BY store_id</pre><p>This is effectively grouping by the month of the entered date, the year of the entered date, and the store id. It gives us the exact partitions that we want!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/42013f3292a398012c42e7f066337153/href">https://medium.com/media/42013f3292a398012c42e7f066337153/href</a></iframe><p>Now the next step is to apply a where clause that selects only the sales with the highest rank. Since we can’t apply a WHERE clause to an aliased column that is not on the table itself, we have to use a subquery in our FROM statement:</p><pre>SELECT store_id, mm, yyyy, amount, entered_at_rank FROM (SELECT store_id, EXTRACT(month from entered_at) as mm, EXTRACT(year from entered_at) as yyyy, amount, rank() OVER (PARTITION BY concat(extract(month from entered_at), extract(year from entered_at), store_id) ORDER BY entered_at DESC) AS entered_at_rank FROM sales ORDER by entered_at_rank) as t ORDER BY store_id</pre><p>This results in exactly the same table as above, but now we can use a WHERE clause on entered_at_rank like this:</p><pre>SELECT store_id, mm, yyyy, amount, entered_at_rank FROM (SELECT store_id, EXTRACT(month from entered_at) as mm, EXTRACT(year from entered_at) as yyyy, amount, rank() OVER (PARTITION BY concat(extract(month from entered_at), extract(year from entered_at), store_id) ORDER BY entered_at DESC) AS entered_at_rank FROM sales ORDER by entered_at_rank) as t WHERE entered_at_rank = 1 ORDER BY store_id</pre><p>Which results in</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0d8b0ab2ac4259db3cc8f33550f1b844/href">https://medium.com/media/0d8b0ab2ac4259db3cc8f33550f1b844/href</a></iframe><p>There is a problem though! The store with an id of 3 has multiple sales for the same month with the same rank (since they have the same amount). What to do?</p><h4>Row Number to the Rescue</h4><p>One thing we can do is use the row_number() window function which will give the number of the current_row within its partition.</p><pre>SELECT store_id, mm, yyyy, amount, entered_at_row FROM (SELECT store_id, EXTRACT(month from entered_at) as mm, EXTRACT(year from entered_at) as yyyy, amount, row_number() OVER (PARTITION BY concat(extract(month from entered_at), extract(year from entered_at), store_id) ORDER BY entered_at DESC) AS entered_at_row FROM sales ORDER by entered_at_row) as t WHERE entered_at_row = 1 ORDER BY store_id</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/434ff9b3d6863071d224aad12671a77c/href">https://medium.com/media/434ff9b3d6863071d224aad12671a77c/href</a></iframe><p>Now we have exactly one sale for each store in a given month/year!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=697bc0ff2ed4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/building-vts/understanding-postgres-window-functions-697bc0ff2ed4">Understanding Postgres Window Functions</a> was originally published in <a href="https://medium.com/building-vts">Building VTS</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Controllers and Content Negotiation: How VTS Builds its API]]></title>
            <link>https://medium.com/building-vts/controllers-and-content-negotiation-how-vts-builds-its-api-570ff7e37840?source=rss-72f0167b79d0------2</link>
            <guid isPermaLink="false">https://medium.com/p/570ff7e37840</guid>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Nassredean Nasseri]]></dc:creator>
            <pubDate>Sun, 01 May 2016 15:36:41 GMT</pubDate>
            <atom:updated>2016-05-01T16:54:12.592Z</atom:updated>
            <content:encoded><![CDATA[<p>At VTS, our core product is an SPA powered by a rails backend, which essentially serves as our API layer. One of the issues we have encountered with the codebase for our web facing API is the proliferation of controllers for the same resource. Often times when building a new feature our inclination is to create a new controller, instead of trying to reuse an existing one. This is driven by a belief that “controllers are cheap”. Recently DHH spoke about how he organizes his controllers, and seemed to echo this philosophy. I thought I would share how we at VTS organize our controllers, which is quite different from the Basecamp approach, but which seeks to solve many of the same problems.</p><h4>The Basecamp Method of Controller Organization</h4><p>The key take away from DHH’s discussion, originally appearing on an episode of Full Stack Radio, is that staying adherent to REST should be paramount. We should never have unrestful routes, and should always stick to index, show, new, edit, create, update, and destroy actions. For DHH, this means that <a href="http://www.fullstackradio.com/32">“whenever I have the inclination that I want to add a method on a controller that’s not part of the default five or whatever REST actions that we have by default, make a new controller! And just call it that”</a>. This means that when dealing with something like an InboxesController, instead of</p><pre><br>class InboxesController &lt; ApplicationController</pre><pre>  def index<br>  end</pre><pre>  def pendings<br>  end</pre><pre>end</pre><p>you would have two separate controllers:</p><pre>class InboxesController &lt; ApplicationController<br> <br>  def index<br>  end</pre><pre>end</pre><p>and</p><pre>class Inboxes::PendingsController &lt; ApplicationController<br> <br>  def index<br>  end</pre><pre>end</pre><p>The objective of this approach is to keep controllers skinny and RESTful. The problem with this approach is that it results in a proliferation of controllers, often for resources which could easily have reused existing controllers by passing in additional query params. For instance, instead of breaking the above into two separate controllers we could have easily used the same InboxesController and passed in an additional param:</p><pre>api/inboxes?status=pending</pre><h4>The VTS Method of Controller Organization — Extended Content Negotiation</h4><p>Like DHH and the folks at Basecamp, we strive towards keeping controllers RESTful and skinny. However, we have a third goal, which is to keep the overall number of controllers for given resource down. Why? For us preventing the proliferation of controllers yields many benefits, mostly surrounding issues which come from code duplication. It also means that the API is organized and easy to understand.</p><p>One potential problem you can face when reusing controllers is that, usually, different clients expect different versions of the same resource. Quite often we can fall into the trap of creating a new controller just to serialize a resource differently. So how do we accommodate these two separate clients that expect the same resource returned, but serialized differently? The answer for us turned out to be relying on <a href="http://www.narwhl.com/2015/03/the-ultimate-solution-to-versioning-rest-apis-content-negotiation/">extended content negotiation</a>.</p><p>In HTTP, content negotiation allows different user agents to request a particular version of a given resource in its desired format. The agent sends several HTTP headers in its request which describe the preferred choice of the user. The server uses these headers to choose which content to serve back to the client. The HTTP/1.1 standard defines a list of headers that may be used in server-driven negotiation. Most of them fall into the category of “Accept Headers”. These include Accept, Accept-Charset, Accept-Encoding, Accept Language, etc. An exhaustive description of these various headers (and many more) can be found <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Content_negotiation">here</a>.</p><p>A typical accept header might look something like this:</p><pre>Accept: application/json</pre><p>In this case the UserAgent is telling the server that it expects a media type of JSON in response to its request.</p><p>“Extended content negotiation” essentially boils down to piggybacking on the existing HTTP mechanisms of content negotiation so that the client can tell the server <em>exactly</em> what it expects the shape of its response to be. In <a href="http://www.narwhl.com/2015/03/the-ultimate-solution-to-versioning-rest-apis-content-negotiation/">this</a> blogpost, the author argues that since REST is already closely tied to the HTTP specification, then “Resources should support more than simply the top-level format of their data — they should specify exactly what data that response contains”. In other words, instead of simply specifying a media type in the Accept header, we can go further, and have our clients ask the server for the exact representation of the resource they need.</p><p>For us designing a RESTful API using principles of extended content negotiation meant adding a version and shape to the accept header. So that the header the client sends would look something like this:</p><pre>Accept: application/json version=1 shape=short</pre><p>Then on the server side, we parse the Accept header to determine how the object should be serialized. At VTS we make heavy use of the ActiveModel::Serializer library provided by rails-api to translate resources into JSON. So the controller would read the header, and translate its version and shape into a constant referencing the correct serializer.</p><h4>The Shapeable Gem</h4><p>We extracted the header parsing logic to a gem called <a href="https://github.com/viewthespace/shapeable">shapeable</a>. Using shapeable allows you to specify the version and shape of a resource using HTTP Accept headers. Shapeable parses the version and shape specified in the accept header, and follows the ActiveModel::Serializer naming convention to decide which serializer the client is expecting.</p><p>So say you have a resource of type Foo and foos_controller.rb that includes our gem and has a show action:</p><pre>class FoosController &lt; ActionController::Base</pre><pre>  acts_as_shapeable(path: Serializers::Foo)</pre><pre>  def show<br>   render json: Foo.new(first_name: &#39;Shawn&#39;), serializer: shape(default_version: 1, default_shape: &#39;short&#39;)<br>  end</pre><pre>end</pre><p>Inside the controller we expose the <em>shape</em> method which is responsible for determining how the client wants the resource serialized.</p><p>Imagine our ActiveModel::Serializer directory structure looks like this:</p><pre>app<br>  serializers<br>    foo<br>      v1<br>        foo_short_serializer.rb<br>        foo_full_serializer.rb<br>      v2<br>        foo_full_serializer.rb<br>        foo_serializer.rb</pre><p>Using the shapeable gem a request might take the following form:</p><pre><br>curl <a href="http://localhost:3000/foos">http://localhost:3000/foos</a> -H &#39;Accept: application/json; version=1 shape=short&#39;</pre><p>The shape method exposed in our controller will reference the Foo::V1::FooShortSerializer constant. If no headers are provided, shapeable will fall back to the defaults provided in the controller method.</p><p>Another client might want the resource to be returned a different way, with a different shape and a different version. So its request might look like this:</p><pre><br>curl <a href="http://localhost:3000/foos">http://localhost:3000/foos</a> -H &#39;Accept: application/javascript; version=1 shape=full&#39;</pre><p>Then the shape method will return Foo::V2::FooFullSerializer.</p><p>This approach has worked quite well for us. It plays well with the rails principle of “convention over configuration” relying on conventional namespacing of serializers, as well as the core principles of REST. It gives our individual controllers flexibility and means that the overall API is well organized and concise.</p><h4>Sources</h4><ul><li><a href="http://www.narwhl.com/2015/03/the-ultimate-solution-to-versioning-rest-apis-content-negotiation/">The Ultimate Solution to Versioning REST APIs: Content Negotiation - The RESTed NARWHL</a></li><li><a href="http://jeromedalbert.com/how-dhh-organizes-his-rails-controllers/">Jerome&#39;s Adventures in Software</a></li><li><a href="http://www.fullstackradio.com/32">32: DHH - Building Basecamp 3 like a Porsche 911 | Full Stack Radio</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Content_negotiation">Content negotiation</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=570ff7e37840" width="1" height="1" alt=""><hr><p><a href="https://medium.com/building-vts/controllers-and-content-negotiation-how-vts-builds-its-api-570ff7e37840">Controllers and Content Negotiation: How VTS Builds its API</a> was originally published in <a href="https://medium.com/building-vts">Building VTS</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How One Ruby Method Let us Delete Thousands of Lines of Code.]]></title>
            <link>https://medium.com/building-vts/how-one-ruby-method-let-us-delete-thousands-of-lines-of-code-445cb884dd2f?source=rss-72f0167b79d0------2</link>
            <guid isPermaLink="false">https://medium.com/p/445cb884dd2f</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ruby]]></category>
            <dc:creator><![CDATA[Nassredean Nasseri]]></dc:creator>
            <pubDate>Sat, 05 Mar 2016 21:55:58 GMT</pubDate>
            <atom:updated>2016-03-06T17:08:43.610Z</atom:updated>
            <content:encoded><![CDATA[<p>At VTS we have a saying: <a href="https://blogs.msdn.microsoft.com/elee/2009/03/11/source-code-is-a-liability-not-an-asset/">code is a liability</a>. As an application grows, legacy code develops. This code might not ever be covered in your production application, but you still incur the cost of maintaining it. Unfortunately, knowing what code is legacy and safe to remove can be difficult in a complex application. In order to try and determine what code was being hit we opted to use a gem called <a href="https://github.com/danmayer/coverband">coverband</a>. Coverband is a ruby gem to measure production code coverage. When enabled it logs every file and line number which has been hit to redis. Coverband can be used as a rack middleware which means that, once configured, we were able to trace the execution path of requests on our production servers.</p><p>Up until very recently, coverband worked by using a method on the Kernel module called set_trace_func. The method set_trace_func takes a blocks as an argument with 6 parameters: The event name, filename, line number, object id, binding, and the name of a class. When called, set_trace_func will invoke the passed in block whenever one of the following events occurs:</p><ul><li>c-call: call a C-language routine</li><li>c-return: return from a C-language routine</li><li>call: call a Ruby method</li><li>class: start a class or module definition</li><li>end: finish a class or module definition</li><li>line: execute code on a new line</li><li>raise: raise an exception</li><li>return: return from a Ruby method</li></ul><p>Here is an example, taken from the documentation:</p><pre>class Test<br>  def test<br>    a = 1<br>    b = 2<br>  end<br>end</pre><pre>set_trace_func proc { |event, file, line, id, binding, classname|<br>  printf “%8s %s:%-2d %10s %8s\n”, event, file, line, id, classname<br>}<br>t = Test.new<br>t.test</pre><p>Output:</p><pre> line prog.rb:11 false<br> c-call prog.rb:11 new Class<br> c-call prog.rb:11 initialize Object<br>c-return prog.rb:11 initialize Object<br>c-return prog.rb:11 new Class<br> line prog.rb:12 false<br> call prog.rb:2 test Test<br> line prog.rb:3 test Test<br> line prog.rb:4 test Test<br> return prog.rb:4 test Test</pre><p>In the case of coverband, the relevant code looks like this:</p><pre>def set_tracer<br>  unless <a href="http://twitter.com/tracer_set">@tracer_set</a><br>    Thread.current.set_trace_func proc { |event, file, line, id, binding, classname|<br>      add_file(file, line)<br>    }<br>   <a href="http://twitter.com/tracer_set">@tracer_set</a> = true<br>  end<br>end</pre><p>From a super high level and ignoring many implementation details the set_tracer method is called on init and calls set_trace_func on the current thread, passing in a block. The block itself calls the add_file method which will log the file and line to redis. Overtime you build up a set of key value pairs in redis where the key is the filename and the value is an array of line numbers. You can then generate a SCOV style report and get a nice output making it easy to see what lines of code are covered in your application!</p><p>But how does set_trace_func actually work? Seeing set_trace_func in action can feel a bit like that classic “ruby magic”. The thing that is most confusing is, how ruby knows when to call the proc. To understand this, we have to take a little detour into how ruby actually runs programs.</p><h4>Tokenization</h4><p>Let’s take the following very simple program:</p><pre>2 + 2</pre><p>When you run the program, ruby first tokenizes the input. During tokenization, ruby steps through the characters one at a time, and groups them together into tokens. Tokenization is the first step in turning the text into an actual program. We can actually see how ruby does its tokenization using the built in ripper tool:</p><pre>require &#39;ripper&#39;<br>require &#39;pp&#39;</pre><pre>code = &lt;&lt;CODE<br>2 + 2<br>CODE</pre><pre>pp Ripper.lex(code)</pre><p>Output:</p><pre>[[[1, 0], :on_int, &quot;2&quot;],<br> [[1, 1], :on_sp, &quot;&quot;],<br> [[1, 2], :on_op, &quot;+&quot;],<br> [[1, 3], :on_sp, &quot; &quot;],<br> [[1, 4], :on_int, &quot;2&quot;],<br> [[1, 5], :on_nl, &quot;\n&quot;]]</pre><p>Each line represents a single token. The first array value is an array which consists of the line and column number. The second array value is the token itself, which corresponds to the actual C parse code. For instance the :on_int token corresponds to the actual tINTEGER token that would be found in ruby’s source code. The third value is the string of characters in the ruby code that correspond to the token.</p><p>Tokenization is responsible only for the process of turning characters into tokens, it is not responsible for determining whether the passed in characters are actually valid ruby. That is the responsibility of the parser.</p><h4>Parsing</h4><p>After the tokenization step, ruby then parses the tokens, grouping them into sentences and phrases as defined by ruby’s grammar rules. Ruby uses the LALR (Look-ahead left reversed rightmost derivation) algorithm to parse the code and generate an AST(abstract syntax tree). I will not detail the algorithm here, but you can see a textual representation of the AST ruby generates for our code by running the following program:</p><pre>require &#39;ripper&#39;<br>require &#39;pp&#39;<br>code = &lt;&lt;CODE<br>2 + 2<br>CODE<br>pp Ripper.sexp(code)</pre><p>Output:</p><pre>[:program,<br> [[:binary,<br> [:<a href="http://twitter.com/int">@int</a>, “2”, [1, 0]],<br> :+,<br> [:<a href="http://twitter.com/int">@int</a>, “2”, [1, 4]]<br> ]]<br>]</pre><p>Ruby has compiled the stream of tokens into an AST, a description of the actual program. The AST is a tree data structure which represents the structure of the program code. The textual output might look a bit confusing, so here is a corresponding graphical output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*Vx1XmtZZ6RBY9X-sNJ9dAQ.png" /></figure><p>We start here with the top level program node. Every ruby generated AST begins with this node. The + operation is contained in a binary node, as in a binary operation. You can see that walking the AST top down and then left to right yields a description of the actual program.</p><h4>Compiling to YARV Instructions</h4><p>As of Ruby 1.9, Ruby uses a virtual machine called YARV(Yet Another Ruby Virtual Machine). This means there is an additional compile step after generating an AST. Ruby recursively iterates over the AST from the top down and compiles each node into YARV instructions. We can see the compiled YARV instructions for our example using built in library tools:</p><pre>code = &lt;&lt;CODE<br>2 + 2<br>CODE</pre><pre>puts RubyVM::InstructionSequence.compile(code).disasm</pre><p>The compiled YARV instructions of this very simple program look like this:</p><pre>== disasm: &lt;RubyVM::InstructionSequence:&lt;compiled&gt;@&lt;compiled&gt;&gt;==========<br>0000 trace 1 ( 1)<br>0002 putobject 2<br>0004 putobject 2<br>0006 opt_plus &lt;callinfo!mid:+, argc:1, ARGS_SIMPLE&gt;<br>0008 leave</pre><p>Let’s examine these instructions carefully.</p><p>First we start with the trace instruction. The trace instruction is exactly what allows us to use set_trace_func. It indicates that a new event has occurred. In this case, the event is <em>line</em>.</p><p>Next YARV pushes the object 2 on the stack as a receiver.</p><p>Then another object 2 is pushed onto the stack as an argument.</p><p>The final instruction, opt_plus says “send the plus message to the receiver (the first 2 object pushed onto the stack) with one argument (the next 2 object on the stack). The ARGS_SIMPLE indicates that the arguments are simple values.</p><p>Now let’s confirm that the trace YARV instruction corresponds to the events hooked into by set_trace_func:</p><pre>set_trace_func proc { |event, file, line, id, binding, classname|<br>  printf “%8s %s:%-2d %10s %8s\n”, event, file, line, id, classname<br>}<br>2 + 2</pre><p>Output:</p><pre>c-return example2.rb:1 set_trace_func Kernel<br> line example2.rb:4</pre><p>Curiously, we see two events here, this is because set_trace_func actually traces itself! So we see the first event, <em>c-return</em> or return from a c function call, in this case the built in set_trace_func method, and then the line event we expected to see. The important thing to remember is this. When ruby executes your program it first translates the source code into a stream of tokens. Ruby then parses the stream of tokens into an AST. Finally each node scope in the AST is compiled into a snippet of YARV instructions. These YARV instructions include calls to trace which allow us to hook into internal ruby events.</p><p>This is just one of the many beauties of Ruby. The dynamic nature of the language allows us to do things which would be impossible in other languages, and which can generate real business value. In this case, understanding one simple built in method allowed us to delete thousands of lines of unused code from our production application, as well as the corresponding tests. For us at VTS it means we have faster test suite, and fewer lines of code to maintain. For more information I would highly recommend checking out the coverband gem for yourself. For more information on how ruby tokenizes, parses, and compiles programs, I would recommend Pat Shaughnessy’s “<a href="http://patshaughnessy.net/ruby-under-a-microscope">Ruby Under A Microscope</a>”, a spectacular dive into Ruby’s internals. In a follow up blogpost I would like to detail how we were able to speed up coverband by swapping out set_trace_func for a new ruby class called TracePoint which provides the same functionality as set_trace_func, but which allows us to hook into specific events. Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=445cb884dd2f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/building-vts/how-one-ruby-method-let-us-delete-thousands-of-lines-of-code-445cb884dd2f">How One Ruby Method Let us Delete Thousands of Lines of Code.</a> was originally published in <a href="https://medium.com/building-vts">Building VTS</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Threading in MRI Ruby for Fun and Performance]]></title>
            <link>https://medium.com/building-vts/threading-in-mri-ruby-for-fun-and-performance-34a0e1bc6c70?source=rss-72f0167b79d0------2</link>
            <guid isPermaLink="false">https://medium.com/p/34a0e1bc6c70</guid>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[concurrency]]></category>
            <dc:creator><![CDATA[Nassredean Nasseri]]></dc:creator>
            <pubDate>Thu, 24 Dec 2015 15:00:30 GMT</pubDate>
            <atom:updated>2015-12-24T18:35:08.521Z</atom:updated>
            <content:encoded><![CDATA[<p>Frequently in our applications as software engineers, we run into situations where we want our code to do multiple things at once. This is the problem of concurrency. Concurrency has an infinite number of use cases. One such use case is that of a webserver. If you were to use a non-concurrent webserver, it would only be able to handle one request at a time. Imagine your site received several requests at the same time. Now the webserver must process each request one at a time, unable to move on to the next request in the queue until the previous one has completed. In order to alleviate this, we might use a concurrent webserver which is capable of processing multiple requests at once.</p><h4>Concurrency vs Parallelsim</h4><p>Before I continue any further, I would like to clear up a point of confusion. This is well worn territory, but to quote Rob Pike, <a href="http://blog.golang.org/concurrency-is-not-parallelism">concurrency is not parallelism</a>. Concurrency means multiple paths of execution can be run and complete in the same time period. Concurrency does not mean that these tasks are running at the exact same time. In a concurrent program utilizing threads and running on a computer with a single CPU core, the OS would switch between the threads, and at no point would the threads actually be executing simultaneously, even if they appeared to. Parallelism means the threads are literally executing simultaneously. Imagine an ATM with 2 queues. Only one person uses the ATM machine at a time, and the next person to use the ATM alternates between the two queues. This is concurrency. Now imagine two ATM machines, each with its own queue. This is parallelism.</p><h4>Global Interpreter Lock</h4><p>MRI has a global interpreter lock (GIL). The GIL means that in a multi-threaded context, only one thread can execute Ruby code at any moment in time. Some posit that, due to the GIL, true concurrency is not possible in ruby programs. Even if we were to run our program on multiple cores, the GIL would prevent more than one thread executing at a time. This is a significant tradeoff of the language, but the GIL also means that we don’t have to worry about corrupting data, or race conditions within C extensions. For these reasons, threading is much easier to deal with in Ruby than in many other languages, even if it is less powerful.</p><p>“But hold on!” You might be exclaiming. “If only one thread can execute at a time, how will my code run any faster when using multiple threads of execution?”</p><p>Great question! The answer is that the GIL only applies to ruby operations, and the work that ruby is doing. Things like I/O or querying a database are free to execute on multiple threads at the same time.</p><h4>Basic Threading</h4><p>In Ruby, concurrency can be achieved using threads. Since version 1.9, MRI Ruby has supported native (OS level) threads.</p><p>Take a look at the following code.</p><pre>thr = Thread.new { puts &quot;Hello, thread world!&quot; }</pre><p>Running this program will yield… nothing. The issue is that the main thread creates a new thread, but as soon as it does the program terminates, and the second thread is terminated alongside it. What we have to do is suspend the execution of the main thread and wait for the second thread to terminate. To do this we have to join the thread.</p><h4>Thread.join</h4><p>Thread.join is what allows us to wait for the second thread to terminate. Typically, when a ruby program exits, all running threads will be killed. However, when we join a thread, the execution of the calling thread is suspended until the joined threads have finished running.</p><pre>thr = Thread.new { puts &quot;Hello, thread world!&quot; }<br>thr.join</pre><p>Running the program now will yield “Hello, thread world!” to STDOUT as expected.</p><p>Now lets move on to another example and try to really visualize what happens when we start creating and joining threads.</p><pre>thr1 = Thread.new do<br> puts &#39;a&#39;<br> sleep 2<br> puts &#39;b&#39;<br> sleep 2<br> puts &#39;c&#39;<br>end</pre><pre>thr2 = Thread.new do<br> puts &#39;1&#39;<br> sleep 2<br> puts &#39;2&#39;<br> sleep 2<br> puts &#39;3&#39;<br>end</pre><pre>thr1.join<br>thr2.join</pre><p>Running this program on my machine a few times yields a few different outcomes. Take a look.</p><pre>$ ruby ruby-threading-ex2.rb<br>a<br>1<br>b<br>2<br>3<br>c<br>$ ruby ruby-threading-ex2.rb<br>1<br>a<br>2<br>b<br>3<br>c<br></pre><p>The inconsistent results lead to some interesting conclusions. Though we initialized thr1 first, ruby makes no guarantees that it will finish initializing before thr2. Furthermore, there is not guarantee in what order the blocks passed to each thread will execute.</p><h4>Thread and Fiber Local Variables</h4><p>Often times, we need a way to reach into a given thread and pull out a value. We can do so using one of two methods. The first way is by riding the thread like so:</p><pre>Thread.current.thread_variable_set(&quot;foo&quot;, &quot;bar&quot;). </pre><p>We can also ride the current fiber:</p><pre>Thread.current[&quot;foo&quot;] = &quot;bar&quot;</pre><p>The difference is a matter of scoping. Here is an example from the docs:</p><pre>Thread.new {<br> Thread.current.thread_variable_set(&quot;foo&quot;, &quot;bar&quot;) # set a thread local<br> Thread.current[&quot;foo&quot;] = &quot;bar&quot; # set a fiber local</pre><pre>  Fiber.new {<br>   Fiber.yield [<br>     Thread.current.thread_variable_get(&quot;foo&quot;), # get the thread local<br>     Thread.current[&quot;foo&quot;], # get the fiber local<br>   ]<br>  }.resume<br>}.join.value # =&gt; [&#39;bar&#39;, nil]</pre><p>Thread locals are carried along with threads, and do not respect fibers. That is the only difference we will concern ourselves with here. There will be more on fibers in part 2 of this series of blog posts. For now though, know that we can set fiber locals. The beauty is that we can access the locals after the thread has finished executing. So we might do some computationally expensive work, set the value to a fiber local, and then access them once the thread has finished executing. For instance:</p><pre>threads = []</pre><pre>threads &lt;&lt; Thread.new do<br> sleep(2) # do something expensive<br> Thread.current[:foo] = &#39;result1&#39;<br>end</pre><pre>threads &lt;&lt; Thread.new do<br>  sleep(2) # do something expensive<br>  Thread.current[:foo] = &#39;result2&#39;<br>end</pre><pre>threads.map(&amp;:join).map do |thr|<br> puts thr[:foo]<br>end</pre><pre>$ ruby fiber-local-ex.rb<br>result1<br>result2</pre><p>This is an extremely common pattern when implementing concurrency in ruby.</p><h4>A Practical Example</h4><p>Recently at VTS we rolled out a new filtering system across the entire site. Upon each request, the filters were performing a series of expensive aggregate queries. Each query looked something like this:</p><pre>def deal_types<br> Deal<br> .where{ deals.id.in(my{ deal_ids } ) }<br> .group{ type }.pluck_all(<br> &#39;deals.type as item_id&#39;,<br> &#39;deals.type as label&#39;,<br> &quot;sum(case when deal.id in (#{ deal_id_subset exclude: :types }) then 1 else 0 end) as count&quot;<br> )<br>end</pre><p>The result set of all the queries was serialized as a hash as follows:</p><pre>def as_json<br> {<br>   deal_types: deal_types,<br>   …<br> }<br>end</pre><p>The queries ran one at a time, and the filter response began timing out. After tuning the queries as best we could, we still had timeout issues. One of our engineers came up with the solution to use threads and run the queries concurrently.</p><pre>def parallelize &amp;block<br> Thread.new do<br>   Thread.current[:output] = yield<br>   ActiveRecord::Base.clear_active_connections!<br> end<br>end</pre><p>The new queries were then called and serialized as follows.</p><pre>def as_json_paralellized<br> {<br>   deal_types: parallelize { deal_types },<br> }.each_value(&amp;:join).map{|k, v | [k, v[:output]] }.to_h<br>end</pre><p>Each query operates in its own thread. We then join the threads and return the resultant fiber locals. Benchmarks revealed this method to be significantly faster, with about a third as much User CPU time (the number on the far left), and wall clock time (the number on the far right). These benchmarks were taken on a local server, and not on our production application.</p><pre>viewthespace(dev)&gt; puts Benchmark.measure { as_json }<br>0.310000 0.020000 0.330000 ( 0.415927)<br>nil<br>viewthespace(dev)&gt; puts Benchmark.measure { as_json_paralellized }<br>0.100000 0.020000 0.120000 ( 0.154479)<br>nil</pre><p>The reason the concurrent version runs faster is because, as I said earlier, the GIL only cares about ruby work. After the SQL query is called, the ruby process releases the GIL as it waits for the database to respond. This is an ideal issue for concurrent ruby since I/O operations do not factor into the GIL.</p><p>Notice that we must call</p><pre>ActiveRecord::Base.clear_active_connections!</pre><p>in order to return the connections used by the current thread back to the pool. Turns out that when a thread running a query terminated, its connection was not automatically returned the pool.</p><p>Additionally, when we first deployed this code, we ran into errors where our unicorn workers would run out of ActiveRecord connections. We had stuck with the default limit of 5 maximum connections per worker. But in this case we were going to surpass that, because each thread we spawned required its own database connection. Since there were 7 aggregate queries, we bumped the limit up to 8. One connection for each possible thread running an aggregate query, and one for the main thread.</p><p>The takeaway here is that, while we did see significant performance gains, it was obvious that we were going “outside the framework” in a way that added complexity, and might seem un-rubyish. When it comes to your own application, consider these tradeoffs before deciding which solution to implement.</p><p>I hope this article has made threading in ruby a little easier to understand and shown how it can be used practically in a modern application. Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=34a0e1bc6c70" width="1" height="1" alt=""><hr><p><a href="https://medium.com/building-vts/threading-in-mri-ruby-for-fun-and-performance-34a0e1bc6c70">Threading in MRI Ruby for Fun and Performance</a> was originally published in <a href="https://medium.com/building-vts">Building VTS</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ruby Metaprogramming by Example]]></title>
            <link>https://medium.com/building-vts/ruby-metaprogramming-by-example-612526d0b72?source=rss-72f0167b79d0------2</link>
            <guid isPermaLink="false">https://medium.com/p/612526d0b72</guid>
            <category><![CDATA[metaprogramming]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <dc:creator><![CDATA[Nassredean Nasseri]]></dc:creator>
            <pubDate>Fri, 20 Nov 2015 00:00:00 GMT</pubDate>
            <atom:updated>2015-12-16T16:17:59.748Z</atom:updated>
            <content:encoded><![CDATA[<p>In Ruby the term metaprogramming refers to the dynamic nature of the language, which allows you to define and redefine methods and classes at runtime. Metaprogramming is often presented as a very nebulous and dangerous concept, one that is difficult to explain and hard to wrap your head around, and thus should be avoided. I’d like to to take some time to show a few powerful uses of metaprogramming techniques in real live code.</p><p>One of the most common, and most misunderstood, aspects of ruby programming is the monkey patch. The monkey patch refers to the ability for ruby to dynamically define and override methods on existing classes and modules at runtime. For instance:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8f2d1c74ec638ebeb81081f40789d7d1/href">https://medium.com/media/8f2d1c74ec638ebeb81081f40789d7d1/href</a></iframe><p>This is admittedly not a very useful monkey patch, but it demonstrates that we can reach into any class, including core classes like Array, and modify it on the fly. The monkey patch is actually just a symptom of a more general paradigm in ruby.</p><h3>Open Classes</h3><p>In Ruby, class definitions are quite flexible.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a9144c74718e9f8b863dbf0742ede7c5/href">https://medium.com/media/a9144c74718e9f8b863dbf0742ede7c5/href</a></iframe><p>Ruby executes the body of the class definition as it would any other code. Interestingly the class keyword does not create the C class twice, which is what allows our earlier example of monkey patching to work. Take a look at the following example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/64c974a1711ca66edd90e3c02b6c011e/href">https://medium.com/media/64c974a1711ca66edd90e3c02b6c011e/href</a></iframe><p>In the first case, class B does not exist, so Ruby defines the class and method1. The second time class B is referenced, the class exists, so instead of redefining class B, it opens the existing class and defines method2 there. The method1 is still accessible because it is still the same class.</p><p>When opening a class we can even reference class level instance variables.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/406b23ce78019746be54ecd6afa106f0/href">https://medium.com/media/406b23ce78019746be54ecd6afa106f0/href</a></iframe><p>Now its time to see some examples of metaprogramming in action. Lets take a look at the Awesome Print gem. Awesome Print is a gem for pretty printing Ruby objects. Awesome Print works with IRB as well as Pry, but for the time being, we will be focused on the IRB code path. For those that might now know IRB is the Ruby REPL distributed with MRI, and written in ruby. The repository can be found here: <a href="https://github.com/michaeldv/awesome_print.">https://github.com/michaeldv/awesome_print.</a></p><p>To use AwesomePrint, first install the gem.</p><pre>$ gem install awesome_print</pre><p>Then in your ~/.irbrc</p><pre>require “awesome_print” AwesomePrint.irb!</pre><p>Taking a look at the project we see that awesome_print.rb has two main files, inspector and formatter, and then a number of core extensions which do various monkey patches on core ruby classes. Lets take a look at the irb! method defined on the inspector class. This function is responsible for intercepting IRB output and formatting it appropriately, in other words it is the “hook” into IRB’s output, intercepting what is outputted and replacing it with its own formatting logic.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/da4ca5d3d88f1f98d77130bb4b340d7a/href">https://medium.com/media/da4ca5d3d88f1f98d77130bb4b340d7a/href</a></iframe><p>Looking through the IRB source on line 661 we see the method output_value. If we monkey patch it like so, check what happens:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/915a9431281d276fe723788df0dd97e1/href">https://medium.com/media/915a9431281d276fe723788df0dd97e1/href</a></iframe><p>So we can see that this is the method that prints to STDOUT. Returning back to the inspector irb! method, we see that this is not quite the same code as we had. Instead of opening up the class using the class keyword we use a class_eval.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a92e31a1fb1167fcd083b063e93c9428/href">https://medium.com/media/a92e31a1fb1167fcd083b063e93c9428/href</a></iframe><p>The class_eval method allows us to execute code in the context of a class. This allows us to open up classes without the class keyword. We can’t have a class definition in a method body, so instead we can use class_eval, which allows us to monkey patch the output_value method dynamically. The class_eval method is very powerful, and allows us to completely redefine classes at runtime.</p><p>Lets take a look at another metaprogramming trick used in AwesomePrint. Open up lib/awesome_print/formatter.rb and take a look at the format method:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/83dfac858cfa0e5c3519b65126b9d31a/href">https://medium.com/media/83dfac858cfa0e5c3519b65126b9d31a/href</a></iframe><p>The format method is the main entry point to format an object. After determining the class of the object it is about to format, the method dynamically calls the corresponding formatter using send.</p><p>The final trick I’d like to show is located lib/awesome_print/core_ext/kernel.rb. This file contains extensions on the core Kernel class. This example comes from the book <em>Metaprogramming Ruby</em> by Paolo Perrota.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d2e7e9d0dd938fdf8a561b019c6e763b/href">https://medium.com/media/d2e7e9d0dd938fdf8a561b019c6e763b/href</a></iframe><p>Here we can see that AwesomePrint has opened up the Kernel module, and is defining two methods ai and ap. Why define them on the Kernel module? Since Kernel is included in Object, and object is in the ancestor chain of nearly every Ruby class, defining a method within Kernel is a handy way of making it available nearly everywhere.</p><p>I hope you enjoyed this little intro on Ruby metaprogramming. To gain a deeper insight into Ruby metaprogramming, I highly suggest Palo Perrotta’s book which you can find here: <a href="https://pragprog.com/book/ppmetr2/metaprogramming-ruby-2.">https://pragprog.com/book/ppmetr2/metaprogramming-ruby-2.</a></p><p><em>Originally published at </em><a href="http://building.vts.com/blog/2015/11/20/ruby-metaprogramming-by-example/"><em>building.vts.com</em></a><em> on November 20, 2015.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=612526d0b72" width="1" height="1" alt=""><hr><p><a href="https://medium.com/building-vts/ruby-metaprogramming-by-example-612526d0b72">Ruby Metaprogramming by Example</a> was originally published in <a href="https://medium.com/building-vts">Building VTS</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>