<?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 Filippos Vasilakis on Medium]]></title>
        <description><![CDATA[Stories by Filippos Vasilakis on Medium]]></description>
        <link>https://medium.com/@vasilakisfil?source=rss-9af304883e1b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*WGECfo2DMqvADScd25fRlA.jpeg</url>
            <title>Stories by Filippos Vasilakis on Medium</title>
            <link>https://medium.com/@vasilakisfil?source=rss-9af304883e1b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 18:19:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vasilakisfil/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[From Media Types to MicroTypes]]></title>
            <link>https://medium.com/kollegorna/from-media-types-to-microtypes-6129a5087979?source=rss-9af304883e1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/6129a5087979</guid>
            <category><![CDATA[rest]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[negotiation]]></category>
            <dc:creator><![CDATA[Filippos Vasilakis]]></dc:creator>
            <pubDate>Fri, 19 Jan 2018 12:21:27 GMT</pubDate>
            <atom:updated>2018-02-13T14:41:47.971Z</atom:updated>
            <content:encoded><![CDATA[<p>Has it ever happened to you that, when building an API based on a well-known Media Type, you suddenly realize that it would have been better if you could introduce a small change ? For instance, imagine that you build an API based on <a href="http://jsonapi.org/">JSON:API</a> spec, but you really want to have templated URIs on links.</p><p>Unfortunately you can’t do much about it. Your available options are:</p><ul><li><strong>breaking the Media Type</strong>: the last thing you want because you would break one of the REST’s constraints: self-descriptive messages. By breaking the Media Type that the client accepts, the client won’t understand your content, leading to undefined behavior.</li><li><strong>creating a new Media Type</strong>: not a very easy option because creating a new Media Type is a lengthy, rigorous process and should generally be avoided. But it doesn’t make much sense either: creating a whole new Media Type just for a tiny change?</li><li><strong>creating a profile using the </strong><a href="https://www.ietf.org/rfc/rfc6906.txt"><strong>RFC 6906</strong></a>: saying that our API follows more specific constraints than our announced Media Type seems quite helpful. But is this really what we want to solve here?</li></ul><p>Let’s go over each of these options in detail.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fT4DH6X_qk9i6wcZ8hMseQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/5GwLlb-_UYk?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">David Werbrouck</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h4>Breaking our announced Media Type</h4><p>One of the main REST constraints is that <strong>r<em>epresentations are exchanged via self-descriptive messages</em></strong><em>. </em>This means that the data of the response should follow the Media Type that the client requested and understands. Given that the client negotiated for that Media Type, it should be able to parse and understand any part of the response.</p><blockquote>Interaction is stateless between requests, standard methods and Media Types are used to indicate semantics and exchange information, and responses explicitly indicate cacheability.</blockquote><blockquote>— Roy Fielding</blockquote><p>If our Media Type is weak for our needs (in terms of semantic capabilities) and we require functionality that the Media Type does not describe, or we just want to alter some semantics of our Media Type (like adding URI templates in JSON:API), then we need to define another Media Type which will describe the new semantics and wait until client(s) incorporate the new Media Type changes.</p><p>Breaking our Media Type’s semantics, or just extending them with new functionality, will have exactly the same result for the client: not self-descriptive messages that will require out-of-band information, like documentation, or will lead to undefined behavior. In any case, the result is quite counter productive for the machines and obviously that’s the worst option we could choose, yet it’s a popular one :/</p><h4>Defining and publishing a new Media Type</h4><p>Why not define a new Media Type, just as how our Internet architecture currently works ?</p><p>Well, although that’s technically correct, it leads to many side-effects and problems down the line. One of the the biggest obstacles of such solution is the fact that defining a whole new Media Type is quite tough. Moreover, in theory, when you override a Media Type spec, you need to publish your changes as a complete custom Media Type for <em>humans</em> to go through it and program their client accordingly. Of course, once the client is programmed, the same implementation can be reused for many different APIs that follow this new custom Media Type.</p><p>Creating a complete new Media Type, or even semantically extending an existing one is difficult. If you can do that then that’s great! Probably you are a rock star as well. Unfortunately very few people can do that (hey, that’s why we have the whole <a href="https://en.wikipedia.org/wiki/Request_for_Comments">RFC</a> process!). As a result, what happens in practice is that we just push unpublished (to the machines) changes on our API and then we hand off out-of-band information to the client, like documentation, and demand <em>humans</em> to check them before parsing and using the hypermedia semantics of our API.</p><p>So while this option is the way to go, it’s tough and experience has shown that it’s rarely done, in practice we end up with option 1 through a different path :/</p><h4>The ‘profile’ Link Relation Type</h4><p><a href="http://dret.net/netdret/">Erik Wilde</a> suggested a profiling mechanism of the underlying Media Type through the <a href="https://tools.ietf.org/html/rfc5988">HTTP Link header</a>, that was later published as <a href="https://tools.ietf.org/html/rfc6906">RFC 6906</a>.</p><blockquote>A profile is defined not to alter the semantics of the resource representation itself, but to allow clients to learn about additional semantics (constraints, conventions, extensions) that are associated with the resource representation, in addition to those defined by the media type and possibly other mechanisms.</blockquote><blockquote>— <a href="https://www.ietf.org/rfc/rfc6906.txt">RFC 6906</a></blockquote><p>Essentially, the profile parameter, given that the client understands it, would define <strong>additional, more specific </strong>semantics of the response’s representation that are not defined through the Media Type used. The information for the additional semantics would be found in all responses regardless the client but only the “smarter” clients would be able to parse, understand and use this information whereas the rest would just ignore it.</p><p>Unfortunately the RFC fails to advocate towards reusable profiles:</p><blockquote>While this specification associates profiles with resource representations, creators and users of profiles MAY define and manage them in a way that allows them to be used across media types; thus, they could be associated with a resource, independent of their representations (i.e., using the same profile URI for different media types). However, such a design is outside of the scope of this specification, and clients SHOULD treat profiles as being associated with a resource representation.</blockquote><blockquote>— <a href="https://www.ietf.org/rfc/rfc6906.txt">RFC 6906</a></blockquote><p>By having profiles attached to specific Media Types this results in much less adoptability and flexibility and fails to signal the actual practicability of such architecture. Another issue is the fact that the negotiation part is skipped from the RFC, something that probably is a requirement if we want to target evolvable, sustainable, self-described APIs.</p><p>But I think the most important thing about this concept is that <strong>it solves a different problem</strong>. From my personal talks with Erik, he is not very fond of altering the core semantics of the Media Type but instead add specific ones for the profile specified:</p><blockquote>(…) what drove the RFC is the ability to identify specific extensions/constraints, with the feed/podcast example being a very typical one: feed is a widely used media type, but there also is a good ecosystem of just podcast/media feeds applications. the feed/profile model works well for making sure that one can talk about podcasts, while it always remains clear that a podcast is a regular feed. (…) They are simply a signal saying “i am using media type X but i am using it with additional constraints”</blockquote><blockquote>Erik Wilde</blockquote><p>Essentially, a profile should <strong>never</strong> <strong>ever</strong> alter the semantics of the Media Type used. Instead, it can only add complementary semantics.</p><p>Regardless how powerful the Profile link relation is, our initial problem, which is being able to extend or even override the Media Type’s semantics in a non-backwards compatible but self-descriptive and evolvable way, is still unsolved.</p><h3>MicroTypes to the rescue</h3><p>What if you could keep your Media Type as is and compose it with a small module that would define the semantics of the links on your API? This semantic module could be either specific for <a href="http://jsonapi.org/">JSON:API</a> spec, or even more general one, which would benefit other API designers as well, although probably it would require substantially more thought and rigour.</p><p>For instance, you could publish your basic API as JSON:API with non-templated links but provide the ability for “smarter” clients to ask the more useful API semantics, that include URI templates in the links. How can you do changes like this and still have self-descriptive messages in evolvable and sustainable APIs?</p><p>Through <strong>small</strong>, <strong>reusable</strong>, <strong>configurable</strong> (per API) modules which are both <strong>discoverable</strong> and <strong>negotiable</strong>, called MicroTypes.</p><p>We will host a talk at <a href="http://www.apidays.io/events/paris-2017"><strong>API Days Paris 2018</strong></a>, called “<em>From Media Types to MicroTypes and Introspected REST</em>” in which we will go through this new idea of composable modules in HTTP. The talk will unravel some forgotten (but still valid!) concepts of our Internet architecture, like Media Type parameters and reactive negotiation, in order to bend the existing Internet infrastructure, which has been mostly influenced by REST concepts and use them effectively in HTTP.</p><p>Eventually it will show how configurability capabilities of those modules can alter conventional designs of HTTP-like APIs by offloading hypermedia and other metadata on the side and leading the way towards a <a href="https://medium.freecodecamp.org/rest-is-the-new-soap-97ff6c09896d">closer gap between REST and RPC</a> styles. Stay tuned!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6129a5087979" width="1" height="1" alt=""><hr><p><a href="https://medium.com/kollegorna/from-media-types-to-microtypes-6129a5087979">From Media Types to MicroTypes</a> was originally published in <a href="https://medium.com/kollegorna">Kollegorna</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Clean HTTP OPTIONS handling in Rails]]></title>
            <link>https://medium.com/kollegorna/clean-http-options-handling-in-rails-d8832c98ca51?source=rss-9af304883e1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/d8832c98ca51</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[open-source]]></category>
            <dc:creator><![CDATA[Filippos Vasilakis]]></dc:creator>
            <pubDate>Mon, 20 Nov 2017 12:27:40 GMT</pubDate>
            <atom:updated>2017-12-28T10:41:34.377Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This article has been translated to Japanese by </em><a href="https://medium.com/u/d7524baeb1ed"><em>OreKanegon</em></a><em> </em><a href="https://techracho.bpsinc.jp/hachi8833/2017_12_25/49954"><em>here</em></a><em>. Many thanks!</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AA9bFEsauR5tz1GoaIQemw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/f6j5Dol1H_I?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Natalia Y</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>No matter how powerful Rails is regarding setting up an API, it fells sort when you want to implement handlers for other HTTP methods, like OPTIONS or HEAD. Specifically, you need to specify for each route an endpoint any of those unconventional HTTP methods. For instance if you have a sessions API resource in your Rails routes:</p><pre>namespace :api do<br>  namespace :v1 do<br>    resources :sessions<br>  end<br>end</pre><p>Rails defines the following Routes (along with the route names and helpers):</p><pre>GET     /api/v1/sessions(.:format)    <br>POST    /api/v1/sessions(.:format)    <br>GET     /api/v1/sessions/:id(.:format)<br>PATCH   /api/v1/sessions/:id(.:format)<br>PUT     /api/v1/sessions/:id(.:format)<br>DELETE  /api/v1/sessions/:id(.:format)</pre><p>By default, Rails skips any routes for other non-conventional HTTP methods, like HEAD and OPTIONS. But it actually make sense, you rarely need those methods and when you do, you just need them in one or two endpoints, so existing Rails routing API doesn’t create any problem. It’s easy to append:</p><pre>namespace :api do<br>  namespace :v1 do<br>    resources :sessions do<br>      collection do<br>        match &#39;&#39;, via: :options, action: &#39;options&#39;<br>      end<br>    end<br>  end<br>end</pre><p>which generates the following routes:</p><pre>GET     /api/v1/sessions(.:format)    <br>POST    /api/v1/sessions(.:format)    <br>GET     /api/v1/sessions/:id(.:format)<br>PATCH   /api/v1/sessions/:id(.:format)<br>PUT     /api/v1/sessions/:id(.:format)<br>DELETE  /api/v1/sessions/:id(.:format)<br>OPTIONS /api/v1/sessions(.:format)</pre><p>However, what happens when you want to have an HTTP OPTIONS (or HEAD, etc) handler for all your routes ? You certainly cannot go through each route and add the OPTIONS endpoint..</p><p>In our case, we would like to expose the API request/response JSON (hyper) schemas through HTTP OPTIONS, for the client to know. Note the same schemas that we want to expose are used for testing our API, so they are always updated (in comparison to the documentation).</p><h4>Designing our interface API</h4><p>When I want to implement a new interface, I always start from my interface API design. So what I would like it to be, ideally ?</p><pre>class Api::V1::UsersController &lt; ApplicationController<br>  before_action :authenticate_user!</pre><pre>  def create<br>    #response handler for POST /api/v1/users<br>  end</pre><pre>  def show<br>    #response handler for GET /api/v1/users/:id<br>  end</pre><pre>  options do<br>   #expose options body for OPTIONS /api/v1/users<br>   #expose options body for OPTIONS /api/v1/users/:id<br>  end<br>end</pre><p>Just a class method that takes a block would be fine, after all this method will serve mostly static data. Inside the block we should be able to differentiate between collection (/users) and resource (/users/:id) routes.</p><pre>options do<br>  if is_index?<br>    #expose options body for OPTIONS /api/v1/users<br>  else<br>    #expose options body for OPTIONS /api/v1/users/:id<br>  end<br>end</pre><h4>Implementing our interface API</h4><p>Luckily Rails provides a way to match any Route that matches all routes with a given constraint. In our case, we want to mach all routes that have HTTP method of OPTIONS. In order to do that we can simply add in our Rails routes:</p><pre>match &#39;*path&#39;, {<br>    controller: &#39;application&#39;,<br>    action: &#39;options&#39;,<br>    constraints: { method: &#39;OPTIONS&#39; },<br>    via: [:options]<br>  }</pre><p>and then in our Application controller we need to define a method that handles that route and deligates to the proper controller#options method, depending the url.</p><pre>def options<br>  #delegate to the right controller#options block<br>end</pre><p>Now the most difficult part of that, is to figure out, based on the URL which controller handles the resource indicated by the url. That’s because Rails <a href="http://www.rubydoc.info/docs/rails/ActionDispatch/Routing/RouteSet#recognize_path-instance_method">recognize_path</a> needs 2 parameters in order to figure out the associated method: the url and the actual HTTP method used for that url. In our case however, we have a different HTTP method (OPTIONS) so we need to do some heuristics :)</p><pre>def route_details_for(url)<br>  <a href="http://twitter.com/route_details">@route_details</a> ||= begin<br>    methods = [:get, :post, :put, :patch, :delete]<br>    method = methods[0]<br>    tries ||= 0<br>    route_details = nil<br>    begin<br>      route_details = Rails.application.routes.recognize_path(url, method: method)<br>      raise ActionController::RoutingError, &#39;&#39; if route_details[:action] == &#39;route_not_found&#39;<br>      rescue ActionController::RoutingError =&gt; _<br>      method = methods[tries]<br>      retry unless (tries += 1) == 5<br>    else<br>      return route_details<br>    end<br>  end<br>end</pre><p>So our heuristic is fairly simple: we take the url and loop over most common methods until <a href="http://www.rubydoc.info/docs/rails/ActionDispatch/Routing/RouteSet#recognize_path-instance_method">recognize_path</a> gives us information about the controller and method associated with them.</p><p>The result comes in the form of {:controller =&gt; “api/v1/searches&quot;, :action =&gt; “create&quot; } and it’s easy to convert and constantize the relevant controller:</p><pre>def controller_for(url:)<br>  route_details = route_details_for(url)<br>  name = route_details[:controller].titleize.gsub(&#39;/&#39;, &#39;::&#39;).gsub(&#39; &#39;,&#39;&#39;)<br>  return &quot;#{name}Controller&quot;.constantize<br>end</pre><p>The last part of the implementation of our initial API design is to call the options block from the associated controller (found by controller_for method). While we could certainly call the method of the controller as is, what is better is to change the context of the block, so that we can have access to the request context along with params and etc from inside the block. We can do that using <a href="http://ruby-doc.org/core-2.2.2/BasicObject.html#method-i-instance_exec">instance_exec</a> from Ruby’s BasicObject method that calls a lambda/proc/block by changing the context to the caller’s. You can find more info about this little magical trick <a href="https://blog.kollegorna.se/things-i-learned-developing-ruby-and-rails-apps-over-the-past-3-years-e04ce780f5b1#e4dc">here</a>.</p><pre>def options<br>  return head :ok if controller_for(url: request.url).options.nil?</pre><pre>  return render({<br>    json: instance_exec(<br>      route_details_for(request.url),<br>      &amp;controller_for(url: request.url).options<br>    )<br>  })<br>end</pre><p>We also pass as a parameter the route_details from recognize_path, for convenience just in case it’s needed by the block. Our result is very similar to the one we initially designed:</p><pre>options do |route_details|<br>  if route_details.dig(:id)<br>    #expose JSON (Hyper) schema for /api/v1/users<br>  else<br>    #expose JSON (Hyper) schema for /api/v1/users/:id<br>  end<br>end</pre><h4>The Gem version</h4><p>This pattern becomes more and more common as APIs become the standard way of communicating between different components of our application. Hence, we have gemified this idea in a gem called <a href="https://github.com/kollegorna/rails_http_options">rails_http_options</a>.</p><p>You can expose interesting metadata (like the schemas) to the client by following 3 steps:</p><ol><li>Include rails_http_options in your ApplicationController. This adds a public options method that is supposed to handle HTTP OPTIONS requests, along with a couple private methods</li><li>Add a route that allows rails_http_options to handle the HTTP OPTIONS you want (you can have even tighter constraints, depending on your needs):</li></ol><pre>match &#39;*path&#39;, {<br>  controller: &#39;application&#39;,<br>  action: &#39;options&#39;,<br>  constraints: { method: &#39;OPTIONS&#39; },<br>  via: [:options]<br>}</pre><p>3. Add the options block in resources that HTTP OPTIONS should have a meaningful body:</p><pre>options do<br>  {<br>    schemas: {<br>      accepts: Company.json_schema,<br>      returns: Company.json_schema<br>    },<br>    meta: { max_per_page: 100 }<br>  }<br>end</pre><p>Inside the block you need to figure out how to find the relevant schemas to the requested resource, and usually a model class method or a service object would work fine :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d8832c98ca51" width="1" height="1" alt=""><hr><p><a href="https://medium.com/kollegorna/clean-http-options-handling-in-rails-d8832c98ca51">Clean HTTP OPTIONS handling in Rails</a> was originally published in <a href="https://medium.com/kollegorna">Kollegorna</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ruby performance profiling: an unorthodox approach]]></title>
            <link>https://medium.com/kollegorna/ruby-performance-profiling-an-unorthodox-approach-69c549e3293b?source=rss-9af304883e1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/69c549e3293b</guid>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[metaprogramming]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[performance]]></category>
            <dc:creator><![CDATA[Filippos Vasilakis]]></dc:creator>
            <pubDate>Mon, 06 Nov 2017 16:12:22 GMT</pubDate>
            <atom:updated>2017-11-09T14:22:45.397Z</atom:updated>
            <content:encoded><![CDATA[<p>We have built an app for one of our clients that allows you to search companies from all over the world, based on key properties like name, country etc and supports even more advanced search queries like CEO last name, sales margin etc. In our implementation we have a Rails app that is sitting as a middleman between an old, inflexible API and our shiny new front-end using EmberJS. Basically it acts as an API Gateway and we have employed various performance tricks like memoization on static or rarely changing data as well as caching to the origin data using Redis.</p><p>In our search endpoint, the Rails API after fetching companies data from various sources, it sends all information for each company (which could result to a huge JSON response) to the client. Of course not everything is shown to the user, only a portion of it and a different and better approach could be asking only for the specific fields that the user wants to see at that point.</p><p><strong>But here is the thing</strong>: even though we have applied some optimizations and caching (origin API is <strong>not</strong> being hit most of the times), requests to our heavy /search API endpoint will still take 5 seconds for pagination size of 50 companies. The rendering time is almost linear to the pagination size (so when asking page size of 10, it takes a little less than 2 seconds) which makes sense given the API design we mentioned.</p><p>But in any case, how can we check where is our bottleneck and where should we apply more optimizations?</p><p>That’s not an easy question to answer.<strong> What is even worse, if you are not the original author of the code and you just jumped in you have no idea where to look and from where to start.</strong></p><h3>Flamegraphs</h3><p>Flamegraphs are visualization of the trace stack into a chart that is easy to understand and reason about. Using <a href="https://github.com/MiniProfiler/rack-mini-profiler">rack-mini-profiler</a> or if you have an API, <a href="https://github.com/ruby-prof/ruby-prof">ruby-prof</a> in combination with <a href="https://github.com/oozou/ruby-prof-flamegraph">ruby-prof-flamegraphs</a> as explained <a href="https://www.codementor.io/tylerboyd/finding-performance-bottlenecks-in-your-rails-api-du107r9zt">here</a> you can configure and create a flamegraph, when doing an API call to your heavy endpoint (search endpoint in our case).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kdJ3jwB0mMYl689m9iO9bw.png" /></figure><p>Am I supposed to understand something from here ? Sure, I can see that “somewhere” the Hash#each method is overused, maybe in the Virtus model, maybe in the serializer (which doesn’t make much sense to me by looking the serializers code) but apparently a flamegraph can’t tell us or help us much. Also, we do have some metaprogramming alcohol (not much, just for clean, human friendly shortcuts) which would make things even more complex to understand from a flamegraph.</p><h3>An unorthodox solution</h3><p>So what can we do ? There is something that I had been always wondering about: how do you measure the performance of a Ruby class/object method ?</p><p>Let’s see an example:</p><pre>require &#39;benchmark&#39;</pre><pre>class Foobar<br>  def do_work<br>    hard_work<br>    easy_work<br>  end</pre><pre>  private<br>    def hard_work<br>      1.upto(10000000).map{|i| i/(rand*i)}.sum<br>    end</pre><pre>    def easy_work<br>      1.upto(1000).map{|i| i/(rand*i)}.sum<br>    end<br>end</pre><p>Given this example class, we want to measure how much time do_work takes. Employing the benchmark standard library that’s easy:</p><pre>foo = Foobar.new</pre><pre>puts Benchmark.measure {<br>  foo.do_work<br>}.real #1.1340300309966551</pre><p>which in my computer gives 1.1340300309966551 seconds. However, given that we know the internal implementation of do_work we would like to take some more specific measurements of the underlying methods. That’s easy as well:</p><pre>hard_time = Benchmark.measure {<br>  foo.send(:hard_work)<br>}.real</pre><pre>easy_time = Benchmark.measure {<br>  foo.send(:easy_work)<br>}.real</pre><pre>puts hard_time #1.1774225730041508<br>puts easy_time #0.00013208099699113518</pre><p>Note that what we care is not the absolute numbers, but the relative ones: that the hard_work takes 10000 times more time to finish,, and we should start optimizing from there. That would be the same regardless the environment, cpu etc.</p><p>We have done great, we know how much time it takes for each method in our class. However, in real-world scenarios, we wouldn’t be able to call the class methods directly, because a class could be initialized in a very specific point in our code, with specific data etc. A better approach would be, to be able to measure the performance of each method when running and playing with our app. In order to achieve this, we can do a nice trick: rename the methods of our interest, to a different name and then call and benchmark those from the original method:</p><pre>require &#39;benchmark&#39;</pre><pre>class Foobar<br>  def do_work<br>    hard_work<br>    easy_work<br>  end</pre><pre>  private<br>    def hard_work<br>      result = nil<br>      puts Benchmark.measure {<br>        result = _hard_work<br>      }.real</pre><pre>      return result<br>    end</pre><pre>    def _hard_work<br>      1.upto(10000000).map{|i| i/(rand*i)}.sum<br>    end</pre><pre>    def easy_work<br>      result = nil<br>      puts Benchmark.measure {<br>        result = _easy_work<br>      }.real</pre><pre>      return result<br>    end</pre><pre>    def _easy_work<br>      1.upto(1000).map{|i| i/(rand*i)}.sum<br>    end<br>end</pre><pre>Foobar.new.do_work</pre><p>Now instantly, when we use our class it measures and reports our method’s performance time. If we use some metaprogramming alcohol, we can get even better result :)</p><pre>require &#39;benchmark&#39;</pre><pre>class Foobar<br>  def do_work<br>    hard_work<br>    easy_work<br>  end</pre><pre>  private<br>    def hard_work<br>      1.upto(10000000).map{|i| i/(rand*i)}.sum<br>    end</pre><pre>    def easy_work<br>      1.upto(1000).map{|i| i/(rand*i)}.sum<br>    end</pre><pre>    [:hard_work, :easy_work].each do |meth|<br>      alias_method &quot;_#{meth}&quot;, meth</pre><pre>      define_method(meth) do<br>        result = nil</pre><pre>        puts Benchmark.measure {<br>          result = self.send(&quot;_#{meth}&quot;)<br>        }.real</pre><pre>        return result<br>      end<br>    end<br>end</pre><pre>Foobar.new.do_work</pre><p>As easy as that. This simple idea can be exported in a module and <a href="https://github.com/vasilakisfil/class_profiler/blob/master/lib/class_profiler.rb">along with some more complex stuff</a> it was extracted as a simple gem, named <a href="https://github.com/vasilakisfil/class_profiler">class_profiler</a> which can be used in an Ruby/Rails project to measure and understand the performance of Ruby classes.</p><h3>Class Profiler</h3><p>Let’s see how we can exploit <a href="https://github.com/vasilakisfil/class_profiler">class_profiler</a> gem. In a Rails project, we can start by adding the gem in our Gemfile and appending the Rack middleware that is provided in our application.rb file.</p><pre>config.middleware.use ClassProfiler::Rack</pre><p>Now if we run our application, this alone should give us performance information per-requests. In our case, for our search endpoint request we get the following result:</p><pre>######### Performance Report #########<br>rack time (total time): 4.4568 (100.0%)<br>rack time (number of calls): 1<br>rack time (average time): 4.4568</pre><pre>######### (most time consuming method is at the bottom) #########</pre><p>Ok, so we can see that the whole request/response takes a little less than 5 seconds, measured from Rack.</p><p>In order to beanchmark a class’ methods that <strong>participate</strong> in the request/response cycle, we only need to add include ClassProfiler at the <strong>bottom of each class we are interested to learn how its methods perform</strong>.</p><p>The reason for that is that, before overriding the methods, the methods must have been defined, and when including a module in the top of the class as we usually do, that’s not possible because Ruby first includes the module’s methods in the class and then appends the methods defined in the class body. So by adding it at the bottom, we give time to the Ruby interpreter to attach the class’ methods to the class which means we can iterate over them and manipulate the way we want :)</p><p>So in our little search controller, we can add it at the bottom</p><pre>class Api::V1::SearchesController &lt; ApplicationController<br>  before_action :authenticate_user!</pre><pre>  def create<br>    with_cache(cached_at) do<br>      search = Search.new(current_user, search_request).all</pre><pre>      render({<br>        json: search,<br>        include: :companies,<br>        serializer: SearchSerializer<br>      }.merge(fields_for(search_request.device)))<br>    end<br>  end<br>  #more methods</pre><pre>  include ClassProfiler<br>end</pre><p>And here is what we get from the class profiler:</p><pre>Api::V1::SearchesController#authenticate_user! (total time): 0.05024 (1.1%)<br>Api::V1::SearchesController#authenticate_user! (number of calls): 1<br>Api::V1::SearchesController#authenticate_user! (average time): 0.05024<br><br>Api::V1::SearchesController#_render_with_renderer_json (total time): 1.54602 (34.8%)<br>Api::V1::SearchesController#_render_with_renderer_json (number of calls): 1   <br>Api::V1::SearchesController#_render_with_renderer_json (average time): 1.54602</pre><pre>Api::V1::SearchesController#_render_to_body_with_renderer (total time): 1.54607 (34.8%)<br>Api::V1::SearchesController#_render_to_body_with_renderer (number of calls): 1<br>Api::V1::SearchesController#_render_to_body_with_renderer (average time): 1.54607<br><br>Api::V1::SearchesController#render_to_body (total time): 1.54609 (34.8%)<br>Api::V1::SearchesController#render_to_body (number of calls): 1<br>Api::V1::SearchesController#render_to_body (average time): 1.54609</pre><pre>Api::V1::SearchesController#cleanup_view_runtime (total time): 1.54643 (34.8%)<br>Api::V1::SearchesController#cleanup_view_runtime (number of calls): 1<br>Api::V1::SearchesController#cleanup_view_runtime (average time): 1.54643</pre><pre>Api::V1::SearchesController#render (total time): 1.54645 (34.8%)<br>Api::V1::SearchesController#render (number of calls): 1<br>Api::V1::SearchesController#render (average time): 1.54645</pre><pre>Api::V1::SearchesController#with_cache (total time): 4.3879 (98.7%)<br>Api::V1::SearchesController#with_cache (number of calls): 1<br>Api::V1::SearchesController#with_cache (average time): 4.3879</pre><pre>Api::V1::SearchesController#create (total time): 4.38962 (98.8%)<br>Api::V1::SearchesController#create (number of calls): 1<br>Api::V1::SearchesController#create (average time): 4.38962</pre><pre>Api::V1::SearchesController#send_action (total time): 4.38965 (98.8%)<br>Api::V1::SearchesController#send_action (number of calls): 1<br>Api::V1::SearchesController#send_action (average time): 4.38965</pre><pre>Api::V1::SearchesController#__run_callbacks__ (total time): 4.44014 (99.9%)<br>Api::V1::SearchesController#__run_callbacks__ (number of calls): 1<br>Api::V1::SearchesController#__run_callbacks__ (average time): 4.44014</pre><pre>Api::V1::SearchesController#_run_process_action_callbacks (total time): 4.44021 (99.9%)<br>Api::V1::SearchesController#_run_process_action_callbacks (number of calls): 1<br>Api::V1::SearchesController#_run_process_action_callbacks (average time): 4.44021</pre><pre>Api::V1::SearchesController#run_callbacks (total time): 4.44024 (99.9%)<br>Api::V1::SearchesController#run_callbacks (number of calls): 1<br>Api::V1::SearchesController#run_callbacks (average time): 4.44024</pre><pre>Api::V1::SearchesController#process_action (total time): 4.44329 (100.0%)<br>Api::V1::SearchesController#process_action (number of calls): 1<br>Api::V1::SearchesController#process_action (average time): 4.44329</pre><pre>Api::V1::SearchesController#process (total time): 4.44344 (100.0%)<br>Api::V1::SearchesController#process (number of calls): 1<br>Api::V1::SearchesController#process (average time): 4.44344</pre><pre>Api::V1::SearchesController#dispatch (total time): 4.44358 (100.0%)<br>Api::V1::SearchesController#dispatch (number of calls): 1<br>Api::V1::SearchesController#dispatch (average time): 4.44358</pre><pre>rack time (total time): 4.44424 (100.0%)<br>rack time (number of calls): 1<br>rack time (average time): 4.44424</pre><p>We can still see that Rack takes a bit less than 4.5 seconds, but this time, we can see the actual time of each controller method along with the number of times it was called and the total percentage of time Ruby spent on that, during a request/response, in percentage. And while Rails has a lot of magic, by going through each method as well as its implementation it’s clear what it takes time. So we can focus in those 4 methods:</p><pre>Api::V1::SearchesController#authenticate_user! (total time): 0.05024 (1.1%)<br>Api::V1::SearchesController#authenticate_user! (number of calls): 1<br>Api::V1::SearchesController#authenticate_user! (average time): 0.05024</pre><pre>Api::V1::SearchesController#render (total time): 1.54645 (34.8%)<br>Api::V1::SearchesController#render (number of calls): 1<br>Api::V1::SearchesController#render (average time): 1.54645</pre><pre>Api::V1::SearchesController#with_cache (total time): 4.3879 (98.7%)<br>Api::V1::SearchesController#with_cache (number of calls): 1<br>Api::V1::SearchesController#with_cache (average time): 4.3879</pre><pre>Api::V1::SearchesController#create (total time): 4.38962 (98.8%)<br>Api::V1::SearchesController#create (number of calls): 1<br>Api::V1::SearchesController#create (average time): 4.38962</pre><pre>rack time (total time): 4.44424 (100.0%)<br>rack time (number of calls): 1<br>rack time (average time): 4.44424</pre><p>So it’s obvious that between Rack and our Rails controller, not much time is spent (only 1.2%). The with_create method spends 98% of the time of the request/response cycle. By looking the implementation, we can see that inside that we call, render (which takes 34.8% of <strong>total</strong>) and and Search.new(current_user, search_request).all which should take the other part of with_create method (so around 98–35 ~65%), but not included/shown in the results because at the moment we profile only our controller class.</p><p>We know that rendering JSON in Rails can be a bit slow and optimizing it would be almost a deadend (although inspecting our Serializers and check that we don’t have any crazy computing method would be a nice thing to do), so let’s take a closer look in Search model, by appending the ClassProfiler module at the bottom of Search class.</p><pre>Search#companies (total time): 3.04153 (59.0%)                                                                                                                                                <br>Search#companies (number of calls): 1                                                                                                                                                         <br>Search#companies (average time): 3.04153                                                                                                                                                      <br>                                                                                                                                                                                              <br>Search#with_cache (total time): 3.18406 (61.8%)                                                                                                                                               <br>Search#with_cache (number of calls): 1                                                                                                                                                        <br>Search#with_cache (average time): 3.18406                                                                                                                                                     <br>                                                                                                                                                                                              <br>Search#all (total time): 3.18418 (61.8%)                                                                                                                                                      <br>Search#all (number of calls): 1                                                                                                                                                               <br>Search#all (average time): 3.18418</pre><p>Well, yes exactly that is happening. The Search model implements the actual search and the most critical ones are those shown above. By checking the implementation, we can clearly see that everything boils down to Search#companies (meaning that the other 2 are just wrappers which eventually call that method), so let’s see the implementation of that method:</p><pre>def companies(data)<br>  companies_data = data[&#39;SearchResults&#39;]</pre><pre>  array = []<br>  companies_data.each do |company_data|<br>    array &lt;&lt; Company.new(user).create_from_raw(<br>      company_data, currency_id: currency_id, scale: scale_id<br>    )<br>  end</pre><pre>  return array<br>end</pre><p>Interesting, just a loop that initializes the Company class. So let’s append ClassProiler to that class as well.<strong> Note that we are not interested in the absolute values anymore</strong>, we override and benchmark a hell out of methods, so the more classes we profile, the more time it will take. However, by checking the <strong>percentage of time spent relatively to our enclosed scope</strong>, (which in our case is almost the whole Rails request/response process along with some parts of Rack, depending where we injected the middleware) we can understand where the bottlenecks are.</p><p>So here is what we have:</p><pre>Company#map (total time): 0.32062 (5.1%)<br>Company#map (number of calls): 50<br>Company#map (average time): 0.00641<br><br>Company#latest_value (total time): 0.92402 (14.7%)<br>Company#latest_value (number of calls): 1245<br>Company#latest_value (average time): 0.00074</pre><pre>Company#on_correct_currency (total time): 0.9924 (15.8%)<br>Company#on_correct_currency (number of calls): 4907<br>Company#on_correct_currency (average time): 0.0002<br><br>Company#wrap_with_output_safety_handling (total time): 1.51866 (24.2%)<br>Company#wrap_with_output_safety_handling (number of calls): 4907<br>Company#wrap_with_output_safety_handling (average time): 0.00031<br><br>Company#delegate_number_helper_method (total time): 1.77579 (28.3%)<br>Company#delegate_number_helper_method (number of calls): 4907<br>Company#delegate_number_helper_method (average time): 0.00036</pre><pre>Company#number_to_currency (total time): 1.86273 (29.7%)<br>Company#number_to_currency (number of calls): 4907<br>Company#number_to_currency (average time): 0.00038</pre><pre>Company#as_financial_value (total time): 1.93381 (30.9%)<br>Company#as_financial_value (number of calls): 4907<br>Company#as_financial_value (average time): 0.00039</pre><pre>Company#with_value_items (total time): 3.76546 (60.1%)<br>Company#with_value_items (number of calls): 50<br>Company#with_value_items (average time): 0.07531</pre><pre>Company#create_from_raw (total time): 4.22242 (67.4%)<br>Company#create_from_raw (number of calls): 50<br>Company#create_from_raw (average time): 0.08445</pre><p>So it’s obvious that Company class is created 50 times, the number of our pagination, and that Company#with_value_items is a big bottleneck because</p><ul><li>it spends around 90% of the time that is spent in that class (60.1% of total request/response)</li><li>it’s a method of 65 lines, quite big</li><li>almost everything take place inside a Hash#each block that loops over origin API’s data and possibly creates a new structure out of it. Note that <strong>Flamegraphs</strong> was showing something like that, but we couldn’t figure out where it was coming from!</li><li><strong>it doesn’t initialize/call any other Class</strong>, only helpers of modules included inside Company class, like ActionView::Helpers::NumberHelper</li></ul><p>At the same time, what is more interesting, it’s that as_financial_value along with some other “helper” methods, like number_to_currency are called 4907 times each one! Here is the implementation of as_financial_value :</p><pre>def as_financial_value(value)<br>  number_to_currency(value, unit: &#39;&#39;, precision: 1)<br>end</pre><p>So basically it calls number_to_currency which is defined in Rails module ActionView::Helpers::NumberHelper , and <strong>this alone spends a little less than 30% of the whole request/response time.</strong></p><p>So even though Company#with_value_items should be the first method we should start looking optimizing, the real bummer and low hanging fruit is a single method, number_co_currency, that comes straight from Rails helper module ActionView::Helpers::NumberHelper, that takes 1.5+ seconds in total (=summed for all calls) of our total response time.</p><p>Is there any faster way of converting a number to currency format ?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=69c549e3293b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/kollegorna/ruby-performance-profiling-an-unorthodox-approach-69c549e3293b">Ruby performance profiling: an unorthodox approach</a> was originally published in <a href="https://medium.com/kollegorna">Kollegorna</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[3+ years of Ember, 6 months of React]]></title>
            <link>https://medium.com/kollegorna/3-years-of-ember-6-months-of-react-34ce909a5ce1?source=rss-9af304883e1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/34ce909a5ce1</guid>
            <category><![CDATA[emberjs]]></category>
            <category><![CDATA[ember]]></category>
            <category><![CDATA[framework]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Filippos Vasilakis]]></dc:creator>
            <pubDate>Tue, 24 Oct 2017 12:35:55 GMT</pubDate>
            <atom:updated>2017-11-01T10:16:35.211Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yl_K-aaEBGBSOKip4YwrZw.jpeg" /></figure><h4>TL;DR: A framework is always nice to have, especially when developing a fast-growing product or when you want to have a maintainable codebase in a volatile team</h4><p><em>Update: This article was translated in Russian by </em><a href="https://medium.com/u/d78d08d900bd"><em>Dan Steshenko</em></a><em> and published </em><a href="https://medium.com/devschacht/filippos-vasilakis-3-years-of-ember-6-months-of-react-973b9c1acb61"><em>here</em></a><em>. Thanks dude!</em></p><p>I still remember my first days in Ember: it was a little more than 3 years ago when Ember was in version 1.5.7. Client requirements was to “work offline as well” and probably as a Rails shop, it felt right to go for a framework that follows Rails philosophy of convention over configuration. At that time I had just seen ember-cli (an alternative of Ember kit), that was supposed to help you with setting up your Ember app and had some Rails-inspired generators like ember generate route Index. I never really liked generators in Rails, I never used them anyway but ember-cli was good to have mostly because it could package your app easily: it was a tool where you could work with and without it you would have to set up/include the scripts, etc. yourself, something that reminded me front-end development of the past decade. I clearly remember wondering myself if I did the right choice to setup the Ember project using ember-cli.</p><p>After going through the whole documentation of “the framework for creating ambitious web applications” I sat down and started creating my first routes and templates, following the designer’s specifications. At that time, Ember was both magical and awful. Magical because I had never seen anything like that, it was my first experience with<strong> reactive programming</strong> and to be honest, it took me a while to figure out that classic software engineering patterns don’t always work for reactive programming. Also, ember-cli provided out of the box ES6 support which made JavaScript development a joy again. On the other side, working on what was called at that time handlebars was awful and I still remember the ugliness of bind-attr if you wanted to bind a property of a component or controller (yes, at that time controllers were a thing!) to an html tag. Working on handlebars was sometimes unpleasant, but hey, that was in 2014 when React hadn&#39;t even been announced and the only real alternative, full-stack front-end framework, was AngularJS.</p><p>3+ years fast forward, at Kollegorna we have taken on more Ember projects and I have personally done a lot of Ember on the side from small apps to huge ones. All that time I loved Ember because it makes me super performant: if you asked me to create a prototype for a client in Ember + Rails or in plain Rails, I would definitely go with Ember: I don’t even need an API, I will just setup the <a href="https://github.com/locks/ember-localstorage-adapter">local storage adapter</a>, structure the models the way I want, add some factories for test data and start coding the prototype. And when we are done with the API as well, we just switch the adapter to the one that fits our API.</p><p>When you have actually worked with frameworks that allow you to update the DOM that easily, it’s not fun going back to the conventional way of setting up a web page, like Rails views. It wouldn’t be an overstatement to say that Ember has changed my way of thinking, especially in complex DOM elements, like forms. And if handlebars felt primitive, HTMLBars which Ember 2.0 introduced, is very powerful, or at least powerful enough that you don’t need something more. But what I mostly love about Ember is that I deal with a framework and that itself has many bright sides, like the addon system. Maybe because I am not a front-end developer by nature, maybe because I don’t like reinventing the wheel, the feeling that I get when I just install a simple addon and use it seamlessly in the templates is super productive.</p><h3>A React adventure</h3><p>6 months ago, I was informed that I would work closely with a client that wanted to create a new front-end app on React. To be honest I was super happy about it. <strong>Finally</strong>, I would have some hands-on experience with the thing called React and its ecosystem. Everyone has been talking about React, the data-down-actions-up pattern was so revolutionary, that even Ember adopted it (= added better support for it) and I won’t be lying if I say that the Ember community has been influenced by React patterns, taking probably the things that make most sense. I was super happy about it.</p><p>The first day I started working with React I sat down and read the official docs. After 3 years of experience with Ember, I could not only grasp React in a few hours but also understood pretty well why things are like that along with common patterns when using it. In essence, I would say that a <a href="https://reactjs.org/docs/react-component.html">React component</a> isn’t much different from an <a href="https://emberjs.com/api/ember/2.15.3/classes/Ember.Component">Ember component</a>. Everything seemed great and I was super excited.</p><p>Unfortunately as time passed I started to realize that React and its ecosystem is missing some crucial things that you would otherwise expect to find in a regular front-end framework like EmberJS, AngularJS, VueJS and the rest.</p><h4>Webpack is hard, yet it becomes de-facto standard</h4><p>6 months into the React project, I never really touched webpack. However I <strong>did</strong> try to understand it through its documentation and tutorials but never really grasped much. To me it seems like Webpack is becoming a de-facto standard in front-end development (unfortunately, because it seems a bit complex), but I never had any problem with Ember. I think the closest in Ember is Broccoli in combination with ember-cli, which both are very easy to understand.</p><p>In Ember you can create and literally deploy an app in 5 minutes after you start on on <a href="https://surge.sh/">Surge</a> (or even using server-side rendering using <a href="https://github.com/ember-fastboot/ember-cli-fastboot">fastboot</a> on <a href="https://www.heroku.com/">Heroku</a>), and I think that’s a big win. For Webpack I have heard many stories that took developers from 1 to 3 days to set it up correctly, which makes me a bit sad :(</p><h4>React is great but it’s just the view layer</h4><p>In case you haven’t figured it out yet, React itself is just the view layer. If you want to have a full page app, you need at least a routing library, like <a href="https://github.com/ReactTraining/react-router">react-router</a> and a state management like <a href="https://github.com/reactjs/react-redux">react-redux</a>.</p><p>While this might sound good for a lot of developers that are not in favor of frameworks, keep in mind that in this case <strong>you make your core code dependent on your various libraries</strong> that you will need, meaning that you might have to digest their quirks or the maintainers decisions (like breaking all APIs in the next released version...). Also note that libraries are developed asynchronously to each other (and from React) making the maintenance of the code over the years more difficult.</p><h4>react-router is not a good library</h4><p><a href="https://github.com/ReactTraining/react-router">React-router</a> is the de-facto routing library for React and surprisingly it’s not a good one. Something like <a href="https://github.com/larrymyers/react-mini-router">react-mini-router</a> or even <a href="https://github.com/iyobo/react-spoon">react-spoon</a> which has only 5 stars on Github, as I’m writing this, could even be a wiser choice than react-router.</p><p><strong>Major breaking changes in every version</strong></p><p>We used react-router V4 and guess what V4 means: on every version there has been a complete rewrite and there have been major breaking changes. Isn’t that bad enough ?</p><p>In comparison Ember’s router has hardly changed at all over the past 3 years, and that’s why you need an RFC-driven way of doing things and, possibly but not necessarily, a framework. Maybe except a small change when you declare the routes in router.js, that probably would take you at most half an hour to update. And all changes had <strong>deprecation warnings</strong> with information how to update on many previous releases before the final release with the breaking changes.</p><p><strong>No named routes</strong></p><p>What is worse, you cannot have named routes, as it is considered an <a href="https://github.com/ReactTraining/react-router/issues/1514#issuecomment-122011215">anti-pattern</a>. Am I the only one here that thinks named routes are crucial to modern web development? Here are 2 reasons:</p><ol><li>I understand that most sites are in English but it happens that people are developing sites in other languages as well, and URLs is not an exception here. Do I really have to type in Chinese every time I need to redirect/link to a route ?</li><li>Isn’t it better if you have one place where you can declare all your routes ? With react-router, I felt that routes were flowing all over the place, and if you jump to a new React project you need to open many files before you understand what’s going on.</li></ol><p>When jumping in an Ember project, the first thing you take a look, is the router.js file, where all the routes are declared. By looking only this file you can instantly understand roughly how the UI/flow looks like, and from there you can move on to the right files to do any necessary changes.</p><p>Given that we don’t have named routes, what can we gain with the React-Router’s structure? In theory, if you use and declare the routes in the correct places, you should be able to add or remove code and features from your codebase with just removing or adding files with no more configuration. I haven’t done anything like that into practice with React and I am wondering if putting this theory in practice will actually work due to coupling from other dependencies or needed code.</p><p><strong>Routes !== components</strong></p><p>One thing that I disliked about React ecosystem is the approach that everything can be a component. I don’t think this logic always works and I like Ember’s approach to that. You really want Routes (you can name them page components) to be distinctly different than a regular component. A route should have different hooks than a component, handling url params, loading/error states, instant redirects, authorization of the route, different lifecycle, what comes first, what comes last, when they fire up and so many other things. We need some help from the library or framework that we use, to achieve these kind of stuff. Otherwise we have to figure out a way of doing these things and I don’t believe that all developers are capable of writing clean, maintainable, testable and scalable code to do that.</p><p>A React component cannot always play the role of a route/page handler.</p><p><strong>Difficulties with things that should be easy</strong></p><p>How can I redirect after a Redux action? Well an <a href="https://stackoverflow.com/a/42124328/1291118">answer</a> on Stack Overflow reminds me about the benefits of a framework.</p><p>In Ember it has been always has been sane. From a component, you just need to send a route action up in a Route which will catch it and do the desired redirect using <a href="https://www.emberjs.com/api/ember/2.15/classes/Ember.Route/methods/transitionTo?anchor=transitionTo">one line of code</a> and the action’s params.</p><h4>JSX or Handlebars, choice is yours</h4><p>Having worked with Ember’s handlebars, specifically HTMLbars since Ember 2.0, JSX templates looked a bit weird to me only the first month, then it felt natural.</p><p>However, if you asked me now, Handlebars or JSX, I would say to you I am fine with both, but if I had a choice, I would choose Handlebars. One reason is that they allow you to copy/paste plain HTML and it’s gonna just work. Another thing is that I feel it’s easier to grasp what the component does because it’s a new DSL designed for that where as JSX feels like a dirty hack, but maybe that’s my own assumption. I would also suspect that it’s easier to give .hbs to a front-end/designer to do their stuff than handing off the JSX (which I felt that it was leading me to spaghetti code sometimes) but again I might be wrong about that.</p><h4>react-redux is a cool pattern</h4><p>From the very beginning we figured out that we wouldn’t manage to get far with React only. The code-base already had React-Router for routing but we needed something that can manage things on the side, like Ember services, because you can’t inject properties all the way down to all components, it’s not maintainable. <a href="https://github.com/reactjs/react-redux">React-Redux</a> was an obvious choice: Redux has been so popular about managing the state in a React project, we have been hearing it everywhere, actually when working with Ember I was hearing so much about react-redux that it revolutionizes the state management somehow.</p><p>In fact, this library really helped us to offload the components (once we added it most components would become functional) and I liked working with it. The pattern was the same everytime: initialize the state correctly for the thing that you want, add an action, add a reducer if needed, and use the action in the component. Some things took me a while to understand on Redux, but all in all I was happy with it.</p><p>The only problem I could see though is that, once you use react-redux, you get locked in that pattern. Having for instance, half your app using react-redux and half mobx would be super complex, not sure if a framework would solve that issue either.</p><p>One thing I can say is that, in my experience, it’s rarely that you need a global state in Ember and instead you use small services (which essentially compose your global state). I actually think Ember gives you so many tools that makes a global state unnecessary. However, I am not against to it and I would like to try it through <a href="https://github.com/ember-redux/ember-redux">ember-redux</a>.</p><h4>Initializer infrastructure needed</h4><p>Having some critical code running before your app boots is not straightforward in React ecosystem. When I actually needed that, I ended up rendering something empty from the root component, do the stuff I needed and then update the state that would re-render the app with the initialized changes applied.</p><p>In a framework like Ember you get that by design. Actually you even have 2 types of initializers: application initializers and instance initializers. The former run when the project is built, essentially giving you the flexibility to have a place where you can alter prototypes, inject code etc, while the latter runs on the client, when the app boots, helping you in any way, like doing some A/B testing depending the client/user properties.</p><p>Again, in the React ecosystem, <strong>the absence of a framework makes you spend more time on setting up trivial things</strong>, instead of focusing on your product.</p><h4>Functional and OO patterns are mixed together</h4><p>I am not saying it’s a bad thing but for some developers that don’t have the time to spend on digesting all those stuff at once (reactive programming, React, react-redux, react-router, high order components, JSX, etc), in a new project, it could be too much.</p><p>I have heard that MobX is closer to OO principles and fits better if you are not familiar much with functional programming, so maybe I should give that a try.</p><h4>Ember-data equivalent is missing :(</h4><p>I wish ember-data was available as a standalone library. This little thing is just magic, and I really mean it! For instance, if you want to start developing your app, but the backend folks haven’t started with the API yet, you can still attach the local storage or session storage adapter and start developing from there (along with some mock data from <a href="https://github.com/danielspaniel/ember-data-factory-guy">ember-data-factory-guy</a>). Then, once the backend API is finished you just need to swap the addon you use and use <a href="https://www.emberjs.com/api/ember-data/2.16/classes/DS.RESTAdapter">RESTAdapter</a> or <a href="https://www.emberjs.com/api/ember-data/2.16/classes/DS.JSONAPIAdapter">JSONAPIAdapter</a> instead. The interface that the application layer uses is still the same.</p><p>Sure, you can do that in React as well, but I doubt all developers can manage to create clean, maintainable and testable interfaces like that let alone architectures that allow you to swap different adapters/serializers smoothly.</p><p>Also, even if the API you are talking to is not entirely RESTish, ember-data gives you the flexibility to talk to it by creating your own serializers/deserializers or even touching the adapters and still preserving the same interface to the application layer. If the API you are working with is consistent in its responses, this process is very easy, you basically need to override a couple of methods.</p><p>It would be a pity if this lib stays only inside the Ember core and not extracted as a separate lib.</p><h3>Dude, are you saying that Ember is perfect ?</h3><p><strong>No</strong>.</p><p>Ember is far from perfect. In fact Ember had a lot of problems when I initially got into it. But it managed to fix those issues by listening/embracing its community and also due to the fact that in a framework it’s easier to evolve without frustrating the users.</p><p>In any case, here are some things that I think every front-end dev should take into account when about to start a new project:</p><h4>A framework is a platform</h4><p>A framework provides you the most useful APIs so that you can exploit it the way you need it, without being attached to a specific pattern and that’s what we should be looking for on frameworks like Ember/Angular/VueJS: a platform. A boring platform you may say, but such platform with good primitives and infrastructure is all you want, so that you can build anything upon it, focus on your product, and not having to re-invent the wheel every time.</p><h4>Performance is not critical, results is all what you want</h4><p>There is a huge run for best performance, do we really need that? I am not sold on the idea that all apps need the ideal performance using libraries like <a href="https://github.com/infernojs/inferno">InfernoJS</a>. In fact, I think what’s more important is to deliver features and have a maintainable codebase that will be easy to change if requirements change.</p><p>Regarding performance in Ember, I think that for now it’s pretty good for the 95% of the front-end apps and given that LinkedIn is <a href="https://www.linkedin.com/pulse/glimmers-optimizing-compiler-chad-hietala/">constantly improving</a> Glimmer’s performance while reducing its size, future seems even more promising for Ember. But if you need more raw power you can always try out the new <a href="https://glimmerjs.com/">Glimmer components</a> or just render React components inside Ember. (and if you want something extremely speedy probably you are already an expert front-end developer and you won’t have a problem with going all-in React ecosystem as well)</p><h4>Great documentation</h4><p>Documentation is one of the most important aspects for a framework or a library. It enables users to exploit the platform at its maximum and actually great documentation motivates users to check it out first, before searching on google for similar problems.</p><p>In my personal opinion, Ember has one of the best documentations I have ever seen in a framework or a library and in fact it has helped me countless times to even discover features of the framework that were not well known.</p><h4>Stability</h4><p>Stability is another key aspect of any framework or library, and communicating that is also crucial (I am looking to you Angular). Stability guarantees that you will not need to spend time/money to keep up to date your codebase and I think that’s something often overlooked in the midst of a hype.</p><p>Ember has been super stable, especially after version 2.0: we upgraded to HTMLbars with no issues, we upgraded to Glimmer VM with 3 deprecation warning and we upgraded so many Ember versions spending so little time. In Ember, <strong>stability is part of the core principles</strong> that even when a <a href="https://github.com/ember-cli/ember-cli/issues/6332">new folder structure</a> (breaking change!) is released soon, a <a href="https://github.com/rwjblue/ember-module-migrator">cli tool</a> will also be released that will automatically convert your deprecated project structure to the new one. Isn’t that great?</p><h4>Listen to your users</h4><p>But what I like mostly about Ember, and I think every framework or library should have it, is that users drive the framework and not a cowboy who felt that he/she should rewrite the whole library with “necessary” breaking changes.</p><p>Ember follows the <a href="https://en.wikipedia.org/wiki/Request_for_Comments">RFC process</a>, for new features or changes, through which anyone can be involved in any step: you can <a href="https://github.com/emberjs/rfcs">create an RFC document</a> describing a new API, it’s detailed design (detailed implementation can be derived later), why it is needed, how it’s going to be compatible with existing APIs or if any breaking changes needed, etc. Then, everyone participates in the discussion and the initial document is transformed to the final through the collaboration and contribution of the whole community, and once it is generally considered as accepted, then Ember core team starts implementing it. You can track such accepted RFCs in <a href="https://www.emberjs.com/statusboard">Ember’s status board</a>.</p><h3>Conclusion</h3><p>Just to be clear: <strong>React is great</strong>. I would be happy to use React again in a project that needs only react, like replacing Phoenix/Rails views with React, or adding React to an existing project as complementary. Or maybe I would like to checkout Ember’s <a href="https://glimmerjs.com/">glimmerjs</a>, which is ember’s equivalent to React, (the view layer of Ember) but that’s mostly because I am already familiar with Ember and I like Ember’s community-driven development.</p><p>But using React (and its ecosystem) for a full web app with many routes/pages/states? No thanks. I think this is a hype and there are much better options to the front-end developer.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=34ce909a5ce1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/kollegorna/3-years-of-ember-6-months-of-react-34ce909a5ce1">3+ years of Ember, 6 months of React</a> was originally published in <a href="https://medium.com/kollegorna">Kollegorna</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[UI controllers in Rails]]></title>
            <link>https://medium.com/kollegorna/ui-controllers-in-rails-bf048409e2c7?source=rss-9af304883e1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf048409e2c7</guid>
            <category><![CDATA[ruby-on-rails]]></category>
            <dc:creator><![CDATA[Filippos Vasilakis]]></dc:creator>
            <pubDate>Tue, 02 May 2017 00:00:00 GMT</pubDate>
            <atom:updated>2017-10-25T15:03:59.256Z</atom:updated>
            <content:encoded><![CDATA[<p>In Rails there have been many times that in your template you might have multiple separate forms and action buttons, usually using remote forms to avoid full-page reload.</p><p>For instance think about a User profile that has remote forms for editing the user basic details (like first name etc), a buttons to subscribe to newsletter, a button that requests password change (it uses an email flow instead of allowing you to set them instantly), a Facebook connect button and many more, and many more, all under the profile/show.erb template.</p><p>Given that that there are so many actions in the same template, you have 2 options to handle them in the backend:</p><h3>Options 1: Create new methods on the same controller</h3><p>The first option is something that I always felt it’s a quick dirty hack. Basically you add custom routes on your profile and map them to meaningful actions. So for instance, to subscribe to a newsletter you would have:</p><pre><strong>class</strong> <strong>ProfilesController</strong> <strong>&lt;</strong> ApplicationController<br>  <strong>def</strong> <strong>newsletter_subscribe</strong><br>    <em>#update user&#39;s newsletter and return js that updates checkbox</em><br>  <strong>end</strong><br><br>  <strong>def</strong> <strong>newsletter_unsubscribe</strong><br>    <em>#update user&#39;s newsletter and return js that updates checkbox</em><br>  <strong>end</strong><br><strong>end</strong></pre><h3>Options 2: Create new separate controllers</h3><p>The second option is to basically create a new controller for each “component” of your UI. Although profile update action could go straight to the ProfilesController, for the rest you will create a separate controller. So for instance, to subscribe to a newsletter you would have a remote form talking to NewslettersController:</p><pre><strong>class</strong> <strong>NewslettersController</strong> <strong>&lt;</strong> ApplicationController<br>  <strong>def</strong> <strong>create</strong><br>    <em>#update user&#39;s newsletter and return js that updates checkbox</em><br>  <strong>end</strong><br><br>  <strong>def</strong> <strong>destroy</strong><br>    <em>#update user&#39;s newsletter and return js that updates checkbox</em><br>  <strong>end</strong><br><strong>end</strong></pre><p>But to be honest this is something that I never liked either: create a brand new controller (+ controller file, template etc) just for toggling a checkbox button ? Too much hassle. What happens in the case when by clicking a master subscription checkbox you get 3 nested checkbox buttons for specific subscriptions? That would mean creating manually 3 new controllers…</p><h3>Nested UI controllers (Rails’ missing option 3)</h3><p>The idea is that we use a tiny DSL inside our controller to create and nest UI-related controller, using a more resty approach:</p><pre><strong>class</strong> <strong>ProfilesController</strong> <strong>&lt;</strong> ApplicationController<br>  controller(:password) {<br>    <strong>def</strong> <strong>reset</strong><br>      <em>#fire an email and add a new flash to inform user</em><br>    <strong>end</strong><br>  }<br><br>  controller(:subscriptions) {<br>    <strong>def</strong> <strong>create</strong><br>      <em>#update user&#39;s master newsletter and return js that updates checkbox</em><br>    <strong>end</strong><br><br>    <strong>def</strong> <strong>destroy</strong><br>      <em>#update user&#39;s master newsletter and return js that updates checkbox</em><br>    <strong>end</strong><br><br>    controller(:interests) {<br>      <strong>def</strong> <strong>create</strong><br>        <em>#update user&#39;s newsletter segments and return js that updates checkbox</em><br>      <strong>end</strong><br><br>      <strong>def</strong> <strong>destroy</strong><br>        <em>#update user&#39;s newsletter segments and return js that updates checkbox</em><br>      <strong>end</strong><br>    }<br>  }<br><br>  controller(:facebook_connect) {<br>    <strong>def</strong> <strong>callback</strong><br>      <em>#handle fb connect</em><br>    <strong>end</strong><br><br>    <strong>def</strong> <strong>redirect</strong><br>      <em>#redirect to fb login</em><br>    <strong>end</strong><br><br>    <strong>def</strong> <strong>destroy</strong><br>      <em>#remove fb connect</em><br>    <strong>end</strong><br>  }<br><strong>end</strong></pre><p>We would also want:</p><ol><li>have the views of the nested controllers again nested under the parent (in our case under app/views/profiles/)</li><li>be able to reference a partial or a nested controlers’ view using nester_controller/partial instead of profiles/nested_controllers/partial</li><li>have the paths of locales of the nested controllers again nested under the parent. For instance when we write the code &lt;%= t(&#39;.subscription_description&#39;) %&gt; in app/views/profiles/subscriptions/_partial template, rails should search under en.profiles.subscriptions.partial for locales.</li><li>Inherit the callbacks of the parent controller <em>by default</em>. I know that this sounds weird but remember that these controllers are under the same UI of the parent controller so for the usual use case we don’t need to repeat ourselves.</li></ol><p>Well after some research and metaprogramming magic this is possible. I have added some comments in order to help you figure out what is going on.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/87b07ce4b2876b16febb9fd087993d58/href">https://medium.com/media/87b07ce4b2876b16febb9fd087993d58/href</a></iframe><p>The code <em>should be</em> self explained due to comments. If not let me know I would happy to help out :)</p><p>Probably (if you read the code!) you will have noticed that we solved (1) (2) and (4) but not (3). Unfortunately I didn’t find any easy way to fix (3). The truth is that it <em>should</em> be possible using custom Resolvers but didn’t invest much time to it because it seemed way to complex to configure this little thingie. Instead, I found out that you can manually set the virtual path of a template by editing the instance variable @instance_path.</p><pre>&lt;%= @vritual_path = &#39;profiles/subcription/something %&gt;</pre><p>You can also use a helper method in ApplicationHelpers: ruby def set_virtual_path proc{|path| @virtual_path = path.split(&#39;/views/&#39;).last.split(&#39;.&#39;).first } end</p><pre>&lt;%= set_virtual_path(__FILE__) %&gt;</pre><p>However I am suspecting that this needs to be cached otherwise it will always touch the filesystem.</p><p>BUT we haven’t quite finished yet: Although we have controllers like ProfilesController::SubscriptionsController etc we need to fix the routes as well:</p><pre>resource :profile, only: [:show] <strong>do</strong><br>    resource :subscriptions, only: [:update, :destroy], controller: &#39;profiles_controller/subscriptions&#39;<br>    resource :password, only: [], controller: &#39;settings_controller/username&#39; <strong>do</strong><br>      post :reset<br>    <strong>end</strong><br>    resource :facebook_connect, only: [:create, :destroy], controller: &#39;settings_controller/facebook_connect&#39; <strong>do</strong><br>      get :callback<br>      get :redirect<br>      delete :destroy<br>    <strong>end</strong><br>    resource :subscriptions, only: [:create, :destroy], controller: &#39;settings_controller/subscriptions&#39; <strong>do</strong><br>      resource :interests, only: [:create, :destroy], controller: &#39;settings_controller/subscriptions_controller/interests&#39;<br>    <strong>end</strong><br>  <strong>end</strong></pre><p>While this works, what I would like to remove the need of specifying the (ugly to be honest) controller because the controller name can obviously figured out by the resource name and the parent resource name.</p><p>An API we can use is the following:</p><pre>resource :profile, only: [:show] <strong>do</strong><br>    resource :subscriptions, only: [:update, :destroy], nested: <strong>true</strong><br>    resource :password, only: [], nested: <strong>true</strong> <strong>do</strong><br>      post :reset<br>    <strong>end</strong><br>    resource :facebook_connect, only: [:create, :destroy], nested: <strong>true</strong> <strong>do</strong><br>      get :callback<br>      get :redirect<br>      delete :destroy<br>    <strong>end</strong><br>    resource :subscriptions, only: [:create, :destroy], nested: <strong>true</strong> <strong>do</strong><br>      resource :interests, only: [:create, :destroy], nested: <strong>true</strong><br>    <strong>end</strong><br>  <strong>end</strong></pre><p>but that would mean that we need to touch the default resource and resources method of ActionDispatch::Routing::Mapper::Resources which is a bad practice.</p><p>Instead we should create a new method that modified the params to be passed down to the resource and resources:</p><pre>resource :profile, only: [:show] <strong>do</strong><br>    <em>#prepend module to use `nested: true` dsl</em><br>    nested_resource :subscriptions, only: [:update, :destroy]<br>    nested_resource :password, only: [] <strong>do</strong><br>      post :reset<br>    <strong>end</strong><br>    nested_resource :facebook_connect, only: [:create, :destroy] <strong>do</strong><br>      get :callback<br>      get :redirect<br>      delete :destroy<br>    <strong>end</strong><br>    nested_resource :subscriptions, only: [:create, :destroy] <strong>do</strong><br>      nested_resource :interests, only: [:create, :destroy]<br>    <strong>end</strong><br>  <strong>end</strong></pre><p>The implementation is quite simple, if you know what to look for :P</p><pre><strong>module</strong> ActionDispatch::Routing::Mapper::Resources<br>  <strong>def</strong> <strong>_parent_resource</strong><br>    self.<strong>send</strong>(<br>      :instance_variable_get, &#39;@scope&#39;<br>    ).<strong>send</strong>(<br>      :instance_variable_get, &#39;@parent&#39;<br>    ).<strong>send</strong>(<br>      :instance_variable_get, &#39;@hash&#39;<br>    )[:scope_level_resource].<strong>controller</strong><br>  <strong>end</strong><br><br>  <strong>def</strong> <strong>nested_resource</strong>(<strong>*</strong>resource, <strong>&amp;</strong>block)<br>    <strong>if</strong> resource.<strong>last</strong>[:controller].<strong>nil?</strong><br>      resource.<strong>last</strong>[:controller] <strong>=</strong> _parent_resource<br>    <strong>end</strong><br><br>    resource(<strong>*</strong>resource, <strong>&amp;</strong>block)<br>  <strong>end</strong><br><br>  <strong>def</strong> <strong>nested_resources</strong>(<strong>*</strong>resource, <strong>&amp;</strong>block)<br>    <strong>if</strong> resource.<strong>last</strong>[:controller].<strong>nil?</strong><br>      resource.<strong>last</strong>[:controller] <strong>=</strong> _parent_resource<br>    <strong>end</strong><br><br>    resources(<strong>*</strong>resource, <strong>&amp;</strong>block)<br>  <strong>end</strong><br><strong>end</strong></pre><p>And we are done!</p><p>(now wait for the infamous WTFs from your colleagues)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*0JJu4AdM6y0qtCvw.jpg" /></figure><p><em>Originally published at </em><a href="https://84601a65.ngrok.io/blog/2017/05/ui-controllers-in-rails/"><em>84601a65.ngrok.io</em></a><em> on May 2, 2017.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf048409e2c7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/kollegorna/ui-controllers-in-rails-bf048409e2c7">UI controllers in Rails</a> was originally published in <a href="https://medium.com/kollegorna">Kollegorna</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rack Reqorder]]></title>
            <link>https://medium.com/kollegorna/rack-reqorder-4ced292770bd?source=rss-9af304883e1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ced292770bd</guid>
            <category><![CDATA[monitoring]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[exception]]></category>
            <category><![CDATA[ruby]]></category>
            <dc:creator><![CDATA[Filippos Vasilakis]]></dc:creator>
            <pubDate>Mon, 20 Mar 2017 00:00:00 GMT</pubDate>
            <atom:updated>2017-10-25T15:09:55.646Z</atom:updated>
            <content:encoded><![CDATA[<p>In our development days in Kollegorna we build various of stuff and fluff.</p><p>One of those is <a href="https://github.com/kollegorna/rack-reqorder">rack-reqorder</a>, a multi-functional rack middleware, targeted (mostly) during the development of APIs. It allows you to:</p><ul><li>record requests/responses</li><li>get statistics over which are the most popular or most slow endpoints</li><li>record errors that might happen in a middleware that is below in the Rack stack.</li></ul><p>But let’s first see what is Rack and why such a tool could be useful.</p><h3>Rack</h3><p><a href="http://rack.github.io/">Rack</a> provides a modular and adaptable interface for developing web applications in Ruby. By wrapping HTTP requests and responses in rack request/response objects, it unifies the API for web servers and web applications (or frameworks) so that developers can focus on the development.</p><p>Rack allows us to have a ‘common protocol’ between various middleware. Each middleware in the rack stack takes the request, processes it if it’s needed and forwards it deeper in the stack. In the deepest level there is, usually, the application code (like Rails controllers). On the way back each rack middleware takes the response, processes it if needed and forwards it in the next middleware.</p><p>For instance, the simplest rack middleware could look like:</p><pre><strong>class</strong> <strong>Foobar</strong><br>  <strong>def</strong> <strong>initialize</strong>(app)<br>    @app <strong>=</strong> app<br>  <strong>end</strong><br><br>  <strong>def</strong> <strong>call</strong>(environment)<br>    rack_request <strong>=</strong> Rack<strong>::</strong>Request.<strong>new</strong>(environment.<strong>clone</strong>)<br><br>    <em>#do work with the request</em><br><br>    http_request <strong>=</strong> record_request(rack_request) <strong>if</strong> conf.<strong>request_monitoring</strong><br><br>    <em>#forward the request</em><br>    status, headers, body <strong>=</strong> @app.<strong>call</strong>(environment)<br><br>    rack_response <strong>=</strong> Rack<strong>::</strong>Response.<strong>new</strong>(body, status, headers)<br><br>    <em>#do work with the response</em><br><br>    <em>#forward the response</em><br>    <strong>return</strong> [status, headers, body]<br>  <strong>end</strong><br><strong>end</strong></pre><p>Foobar middleware only needs to be injected in the Rack middleware. For instance, in rails:</p><pre>Rails.application.config.middleware.insert_after(0 , Foobar)</pre><p>Foobar middleware will run in every request and in every response. Whether it does work on request, on response or on both depends on the middleware itself.</p><p>So in essence, Rack is the place from which you can control everything. Wouldn’t be great to record a request or a response if you wanted to?</p><p>That’s how <a href="https://github.com/kollegorna/rack-reqorder">rack-reqorder</a> was born. We are developing some code on our machine, tests are green, we deploy on staging but the client (EmberJS in our case) seems to get an error. To debug the error when the code has been deployed it’s challenging most of the times.</p><p>Rack-reqorder provides 2 mechanisms to investigate what has happened to the backend:</p><h4>Exception monitoring</h4><p>First it records all errors that happen in a middleware below (even the application code is considered a middleware for Rack). So you don’t have to check the logs all the time:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*m4LDg4h4keOBNGcA.png" /></figure><p>Once an exception takes places, rack-reqorder will record both the request that caused the exception and information about the error, like the exact lines that it happened, the application trace etc.</p><p>The developer can mark filter the exceptions based on environment and status (solved, unsolved), see other instances of the same exception and change the status, like marking it to solved.</p><p>You can think of it as yet another exception monitoring tool :)</p><h4>Request recording</h4><p>While tracking exceptions could also be done by other tools or logging, tracking bugs on production could become quite tricky. When something is not working right for a specific client, but no error is raised, how would you track all its requests/responses ? During the development of an App, especially when the front-end team is different from the backend team a tool like that could become quite handsome.</p><p>Rack-reqorder allows you to start reqording all requests/responses instantly to see what’s going on, why the error happened, based on a header and its value.</p><p>The header could be a custom one (like X-Custom-Header), or just the authentication token of the client that complaints for the bug (like Authorization header along with the api token of the client). By enabling this feature, rack-reqorder will record all requests and responses in a continued timeline for better understanding of the flow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sAZAcXSiohKnCfh4.png" /></figure><p>You have a clear view on the requests flow (which came first, which came last) along with the request and their associated responses objects.</p><h4>And some fluff</h4><p>As a bonus, rack-reqorder records various statistics about the requests/responses by categorizing in route paths. A route path is a requested url combined with the request action (so GET /users is different from POST /users).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ced292770bd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/kollegorna/rack-reqorder-4ced292770bd">Rack Reqorder</a> was originally published in <a href="https://medium.com/kollegorna">Kollegorna</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Things I learned developing Ruby and Rails apps over the past 3+ years]]></title>
            <link>https://medium.com/kollegorna/things-i-learned-developing-ruby-and-rails-apps-over-the-past-3-years-e04ce780f5b1?source=rss-9af304883e1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/e04ce780f5b1</guid>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[tips]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[tricks]]></category>
            <dc:creator><![CDATA[Filippos Vasilakis]]></dc:creator>
            <pubDate>Mon, 30 Jan 2017 00:00:00 GMT</pubDate>
            <atom:updated>2017-11-20T12:40:20.495Z</atom:updated>
            <content:encoded><![CDATA[<p>The article has been translated in Japanese by <a href="https://medium.com/u/d7524baeb1ed">OreKanegon</a>, <a href="https://techracho.bpsinc.jp/hachi8833/2017_11_20/48322">here</a> :)</p><p>In random order:</p><h3>Use rescue_from in top level controller</h3><p>Using rescue_from in the root controller is very helpful for catching any exception happening below. Given that in web apps, most code runs in a request/response cycle this becomes even more helpful Let&#39;s say that you build a simple API. By using rescue_from you can explicitly specify what the app should do when a record is not found (AR throws ActiveRecord::RecordNotFound)</p><pre>rescue_from ActiveRecord<strong>::</strong>RecordNotFound <strong>do</strong><br>  api_error(status: 404, errors: &#39;Resource not found!&#39;)<br><strong>end</strong></pre><h3>Use load_resource on controllers</h3><p>Another pattern I have adopted after seeing a former colleague using it: instead of fetching the necessary resource inside the controller method, use a common controller filter and fetch it there depending on the action.</p><pre><strong>class</strong> <strong>UsersController</strong><br>  before_action :load_resource<br><br>  <strong>def</strong> <strong>index</strong><br>    <em># do something with @users</em><br>  <strong>end</strong><br><br>  <strong>def</strong> <strong>show</strong><br>    <em># do something with @user</em><br>  <strong>end</strong><br><br>  <strong>def</strong> <strong>create</strong><br>    <em># do something with @user</em><br>  <strong>end</strong><br><br>  <strong>def</strong> <strong>update</strong><br>    <em># do something with @user</em><br>  <strong>end</strong><br><br>  <strong>def</strong> <strong>destroy</strong><br>    <em># do something with @user</em><br>  <strong>end</strong><br><br>  <strong>private</strong><br>    <strong>def</strong> <strong>load_resource</strong><br>      <strong>case</strong> params[:action].<strong>to_sym</strong><br>      <strong>when</strong> :index<br>        @users <strong>=</strong> paginate(apply_filters(User.<strong>all</strong>, params))<br>      <strong>when</strong> :create<br>        @user <strong>=</strong> User.<strong>new</strong>(create_params)<br>      <strong>when</strong> :show, :update, :destroy<br>        @user <strong>=</strong> User.<strong>find</strong>(params[:id])<br>      <strong>end</strong><br>    <strong>end</strong><br><strong>end</strong></pre><p>Also related and more advanced is <a href="https://github.com/hashrocket/decent_exposure">decent_exposure</a> although I haven’t had the chance to use it myself yet.</p><p>I kind of disagree with the saying that the “good quality code is always self-explained” for 2 main reasons:</p><ul><li>Good quality code for one developer could be bad quality for another developer (and this is not necessarily bad, everyone has their own style)</li><li>We have all in situations where, due to time and/or budget constraints, you end up making a quick fix just to close an issue because the best (and most self-explanatory) solution would have required 10 times the effort.</li></ul><p>For those reasons, comment your code smells and don’t be ashamed :)</p><h3>Use decorators and presenters</h3><p>There was a saying in Rails community awhile ago: keep your controllers skinny by making your models fat. While I agree with the first part, I disagree with the second :) I think that models should be as skinny as possible, that is, don’t add computed properties to a model that are used only in a special cases. Use a wrapper class for that case (hey! it’s called Decorator!) and expose only the methods that are needed.</p><p>A presenter is like a decorator, only that it takes multiple models.</p><h3>Namespace your workers under your model, call them on after_commit</h3><p>Let’s say that we have a model, User. 90% of the background jobs related to a model are taking place when the model is created, updated or deleted, because this is when data change. This leads to 3 generic workers: User::CreateWorker, User::UpdateWorker, User::DestroyWorker. Try to use those workers, if applicable, in combination with AR callbacks and previous_changes. Call a worker on after_commit. See <a href="http://rails-bestpractices.com/posts/2012/05/02/use-after_commit/">here</a> an explanation of why.</p><h3>Don’t use Postgres array unless it’s something very simple</h3><p>Another thing that although cool, my experience has shown me that it will generate more problems than save you time. Every time that I have tried to use Postgres array, for instance to hold some ids, I have banged my head against the table later. After all, tables are not expensive in databases, JOINs are.</p><p>I would use Postgres array for very small things:</p><ul><li>When I know that the table will hold a small number of elements and won’t get large enough on average (with a small variance on that if possible)</li><li>When the table data doesn’t have anything to do with ids and associations</li></ul><h3>Postgres JSONB is the cool kid in town</h3><p>In contrast to my feelings on Postgres arrays, I love Postgres’ JSONB. We all love a database that has schema and we understand their advantages over schemaless databases, but sometimes you desperately need the simpleness of a schemaless database because you don’t know your schema beforehand. I usually use JSONB in the following cases:</p><ul><li>When I have plenty of small attributes, possibly namespaced by a parent attribute. Using a regular table for this would require a lot of columns.</li><li>When I don’t know what exactly I will save or when building a quick prototype</li><li>When I do object hydration: saving the JSON representation of an object in the DB and being able to rebuild it from the same JSON</li></ul><h3>aasm is cool until you want to initialize in a specific state</h3><p>I love aasm gem. I mean, this thing forces you to have a state machine and it has a very simple DSL for that. Until you want to create an object on a specific state, other than the initial. Then you get issues: hooks don’t run. Either you do some crazy stuff taking into account the internals of aasm or you just accept the fact that you will manually traverse to the specified state of the object (you can create a service for that!)</p><h3>Validating email addresses is hard, just use the gem</h3><p>It’s so funny: everytime I search for an email validation regex on the internet I endup with a different regex. Well, let’s just accept that there isn’t any perfect regex and the best thing you can do is to use the gem.</p><h3>Try to pass only a single instance variable to the view by employing decorators or presenters</h3><p>Yes, something that I am not proud of in Rails: it kind of forces you to use instance variables in order to pass the context from a controller to the view. I think this is a bad practice. We should always instantiate and pass a single object to the view. Sandi Metz says so!</p><h3>Use an exclamation mark when a model instance method saves the model!</h3><p>If your model method modifies the object and saves the changes to the database your method should always end with a bang to denote that. As simple as that.</p><p>People tend to forget (including me!). Stricter APIs in the class level leads to better code quality.</p><h3>Don’t use devise if you just want a simple authentication</h3><p>Too much magic, bro.</p><h3>Use Virtus for defining attributes in a non-AR model to add strictness</h3><p>I used (and I still use) Virtus gem a lot. It allows me to make a simple PORO to look like a <em>model</em> and have some strictness for its attributes. When the attributes become too many, I tend to use my own DSL for Virtus so that I can manipulate them, as you can see below:</p><pre><em># simple module that allows us to reuse defined attributes in serializers</em><br><em># plus some other goodies</em><br><strong>module</strong> VirtusModel<br>  <strong>extend</strong> ActiveSupport<strong>::</strong>Concern<br><br>  included <strong>do</strong><br>    <strong>include</strong> Virtus.<strong>model</strong><br><br>    <strong>if</strong> defined?(self<strong>::</strong>ATTRIBUTES)<br>      self<strong>::</strong>ATTRIBUTES.<strong>each</strong> <strong>do</strong> <strong>|</strong>group<strong>|</strong><br>        group[:attrs].<strong>each</strong> <strong>do</strong> <strong>|attr|</strong><br>          attribute(<strong>attr</strong>, group[:type])<br>        <strong>end</strong><br>      <strong>end</strong><br>    <strong>end</strong><br>  <strong>end</strong><br><br>  class_methods <strong>do</strong><br>    <strong>def</strong> <strong>all_attributes</strong><br>      self<strong>::</strong>ATTRIBUTES.<strong>map</strong>{<strong>|</strong>i<strong>|</strong> i[:attrs]}.<strong>flatten</strong><br>    <strong>end</strong><br>  <strong>end</strong><br><strong>end</strong><br><br><em># an example model</em><br><strong>class</strong> <strong>Model</strong> <strong>&lt;</strong> ActiveModelSerializers<strong>::</strong>Model<br>  ATTRIBUTES <strong>=</strong> [<br>    {<br>      attrs: [<br>        :id, :name, :header_text, :is_visible, :filtering_control,<br>        :data_type, :description, :caregory, :calculation<br>      ],<br>      type: String<br>    },<br>    {<br>      attrs: [<br>        :display_index, :min_value, :max_value, :value_type,<br>        :number_of_forcast_years<br>    ],<br>      type: Integer<br>    },<br>    {<br>      attrs: [:category], type: Array<br>    },<br>    {<br>      attrs: [:is_multi_select],<br>      type: Virtus<strong>::</strong>Attribute<strong>::</strong>Boolean<br>    }<br>  ].<strong>freeze</strong><br><br>  <strong>include</strong> VirtusModel<br><strong>end</strong></pre><p>Being able to iterate over different attribute types or adding kind of <em>tags</em> in a group of attributes makes my life easier :)</p><p>Now that <a href="http://api.rubyonrails.org/classes/ActiveRecord/Attributes/ClassMethods.html">attributes API</a> has landed I guess I will do the same, or something similar with it :)</p><h3>Use memoization when something takes time to be computed (like talking to external API)</h3><p>Goes without saying :)</p><h3>Postgres full text search is good enough for simple things</h3><p><a href="https://github.com/Casecommons/pg_search">pg_search</a> is super easy to set up. However, if you have to optimize Postgres full text search using tvectors, etc, just go with ElasticSearch. It’s not worth it to more time on Postgres.</p><h3>It’s 2017 and we still can’t define what a Service Object is :)</h3><p>Still looking for a clear definition that most people agree on what a service object is and how they should be implemented :)</p><p>In a recent project we followed a pattern that I’d be happy to use again. First we defined a module which once included creates a <em>class</em> method named perform.</p><p>Then on any service we create, we mark the constructor (initialize) as private, which means we can ony call the public class method perform (of course in dynamic languages like Ruby we can always call private methods but we just make it much more difficult).</p><pre><strong>module</strong> PerformerService<br>  <strong>def</strong> <strong>self.included</strong>(base)<br>    base.<strong>send</strong>(:define_singleton_method, :perform) <strong>do</strong> <strong>|</strong>url<strong>|</strong><br>      <strong>begin</strong><br>        <strong>return</strong> self.<strong>send</strong>(:new, url).<strong>send</strong>(:perform)<br>      <strong>rescue</strong> Exception <strong>=&gt;</strong> e<br>        Rails.<strong>logger</strong>.<strong>error</strong>(&quot;#{self.<strong>class</strong>}: Exception raised: #{e}&quot;)<br>      <strong>end</strong><br><br>      <strong>return</strong> <strong>nil</strong><br>    <strong>end</strong><br>  <strong>end</strong><br><strong>end</strong></pre><pre><strong>class</strong> <strong>UrlParser</strong><br>  <strong>include</strong> PerformerService<br>  <strong>private</strong><br>    <strong>def</strong> <strong>initialize</strong>(url)<br>      @url <strong>=</strong> url<br>    <strong>end</strong><br>    <strong>def</strong> <strong>perform</strong><br>      <em>#do all the hard work</em><br>    <strong>end</strong><br><strong>end</strong><br><br>UrlParser.<strong>perform</strong>(&#39;https://kollegorna.se&#39;)</pre><h3>Transform AR error messages the way you want</h3><p>When building an API in Rails usually the errors will follow the JSONAPI style, that is, you will get a message (can&#39;t be blank) and the attribute (user_id) that the message fails.</p><p>We don’t use JSON pointers in this example, but the same idea could apply to that case as well.</p><p>On the client side you handle those two the way you want: you could go to your form and find the user_id input to make it red, or you could just concatenate them and make it one sentence, after some human-friendly transformations, like User id can&#39;t be blank.</p><p>What happens though when the attribute related to the message makes no sense to the user?</p><p>Let’s say that in our app, each user can create a new post. However it’s only possible to create a new post once a day. So in your model you will enforce uniqueness:</p><pre>validates :user_id, {<br>  uniqueness: {<br>    scope: :post_id,<br>    conditions: <strong>-&gt;</strong> { where(&#39;created_at &gt;= ?&#39;, 1.<strong>days</strong>.<strong>ago</strong>) },<br>  }<br>}</pre><p>(yes, yes, you should enforce the same uniqueness on the DB level as well, but we don’t handle the errors in this case because the user must be super (un)lucky to manage to get two requests of his own landing on two different servers (of the same app talking to the same DB) at the exact same time..)</p><p>So the message will look like:</p><pre>{<br>  &quot;title&quot;: &quot;Could not process request&quot;,<br>  &quot;message&quot;: &quot;Something more descriptive here&quot;,<br>  &quot;errors&quot;: [<br>    {<br>      &quot;attribute&quot;: &quot;user_id&quot;,<br>      &quot;message&quot;: &quot;has already been taken&quot;<br>    }<br>  ]<br>}</pre><p>which is not usefull at all to the user. One idea is to use the message option:</p><pre>validates :user_id, {<br>  uniqueness: {<br>    scope: :post_id,<br>    conditions: <strong>-&gt;</strong> { where(&#39;created_at &gt;= ?&#39;, 1.<strong>days</strong>.<strong>ago</strong>) },<br>  },<br>  message: &#39;can only post once a day&#39;<br>}</pre><p>Now the message will look look like: [&#39;user_id&#39;, &#39;can post only once a day&#39;] which is better but still not very useful if you use both attributes.</p><pre>{<br>  &quot;title&quot;: &quot;Could not process request&quot;,<br>  &quot;message&quot;: &quot;Something more descriptive here&quot;,<br>  &quot;errors&quot;: [<br>    {<br>      &quot;attribute&quot;: &quot;user_id&quot;,<br>      &quot;message&quot;: &quot;can only post once a day&quot;<br>    }<br>  ]<br>}</pre><p>Ideally we would like to move the message to the base because it&#39;s not dependant on a specific model attribute but instead it&#39;s a custom, more general, restriction. We can do that by adding a custom DSL in the message:</p><pre>validates :user_id, {<br>  uniqueness: {<br>    scope: :post_id,<br>    conditions: <strong>-&gt;</strong> { where(&#39;created_at &gt;= ?&#39;, 1.<strong>days</strong>.<strong>ago</strong>) },<br>  },<br>  message: {<br>    replace: &quot;user_id&quot;,<br>    with: {<br>      attribute: &quot;base&quot;,<br>      message: &quot;You can only post once a day&quot;<br>    }<br>  }<br>}</pre><pre><strong>def</strong> <strong>replace_errors</strong>(errors)<br>  errors_array <strong>=</strong> []<br>  errors.<strong>messages</strong>.<strong>each</strong> <strong>do</strong> <strong>|</strong>attribute, error<strong>|</strong><br>    error.<strong>each</strong> <strong>do</strong> <strong>|</strong>e<strong>|</strong><br>      <strong>if</strong> e.<strong>is_a?</strong>(Hash) <strong>&amp;&amp;</strong> e[:replace]<br>        errors_array <strong>&lt;&lt;</strong> {<br>          attribute: e[:with][:attribute],<br>          message: e[:with][:message]<br>        }<br>      <strong>else</strong><br>        array_hash <strong>&lt;&lt;</strong> {attribute: attribute, message: e}<br>      <strong>end</strong><br>    <strong>end</strong><br>  <strong>end</strong><br><br>  <strong>return</strong> errors_array<br><strong>end</strong></pre><p>So now you get the error you need exactly under the attribute you want:</p><pre>{<br>  &quot;title&quot;: &quot;Could not process request&quot;,<br>  &quot;message&quot;: &quot;Something more descriptive here&quot;,<br>  &quot;errors&quot;: [<br>    {<br>      &quot;attribute&quot;: &quot;base&quot;,<br>      &quot;message&quot;: &quot;You can only post once a day&quot;<br>    }<br>  ]<br>}</pre><h3>Explicitly use return for methods that are executed for their return value, even one-liners</h3><p>I think the Ruby community has embraced not using return statements but I feel there is no reason for that. Actually I like to add a return statement even in one-liners, when they should be used for their return values and not for their side effects.</p><p>Arguments like about Ruby coolness and expressiveness fall short when it comes to productivity and (kind of) safety.</p><h3>Try to use parentheses unless you write some kind of DSL</h3><p>Same goes here. Adding parentheses doesn’t hurt. Instead, they make your collegue (who happens to work with other languages as well) happier.</p><h3>Add strict boolean types in env variables:</h3><p>I like to use the following snippet in config/sercrets.yml:</p><pre><strong>&lt;%</strong><br>booly_env <strong>=</strong> <strong>-&gt;</strong>(value) {<br>  <strong>return</strong> <strong>false</strong> <strong>if</strong> value.<strong>blank?</strong><br><br>  <strong>return</strong> <strong>false</strong> <strong>if</strong> ([&#39;0&#39;, &#39;f&#39;, &#39;false&#39;].<strong>include?</strong>(value.<strong>to_s</strong>.<strong>downcase</strong>))<br>  <strong>return</strong> <strong>true</strong> <strong>if</strong> ([&#39;0&#39;, &#39;t&#39;, &#39;true&#39;].<strong>include?</strong>(value.<strong>to_s</strong>.<strong>downcase</strong>))<br>  <strong>return</strong> <strong>true</strong><br>}<br>%&gt;</pre><p>This will make it easier to deal with boolean env variables in the code since it makes sure that it will either be true or false.</p><pre>development:<br>  enable_http_caching:  &lt;%= booly_env[ENV[&quot;ENABLE_HTTP_CACHING&quot;] || false] %&gt;</pre><h3>Have a very good reason if using any other DB than Postgres as the primary DB</h3><p>MongoDB used to be the cool kid in town. People took a while to learn Mongo’s shortcomings:</p><ul><li>It’s schemaless. You could say it’s a feature, but in fact it’s a huge drawback. Databases with a schema, allow you to gradually change your schema they way you want, providing you the tools and guarantees. For instance, if I have a column in SQL that is of type Integer, I can transform it in String or Text, add a default or make it non nullable. This is impossible in schemaless databases. You need to do this work on your own, in a higher level (using a programming language). Also, adding an attribute or dropping an attribute is also impossible. Basically you are stuck with the schema you begun with and you either create a new one from the beginning and you make sure that you migrate correctly, or you handle these in the application level.</li><li>They don’t provide transactions.</li><li>No ACID</li><li>I don’t think it’s fast enough for less trivial queries</li></ul><p>Are you sure that you would like to have those issues in your primary DB? I would not. Personally, I feel the only killer MongoDB feature is that of embedding many documents in a parent document. The rest I can probably find them in Postgres (and hey! I will have to care for security updates for only one DB system)</p><h3>Dynamic scope is a cool pattern when nothing else works</h3><p>When we define a closure in Ruby (a proc or a lambda), it encapsulates its lexical scope/environment.</p><p>This means that even if you define a proc at point A in code, if you pass it around and call it at point B, it will still be able to reference variables and anything that is defined inside the lexical scope of point A (where it was defined). To put it in another way, it has “closed its environment”.</p><p>What if we would like to do the opposite? Say we define a proc at point A, that if we call there it makes no sense, but we want to run it at point B and change the lexical scope of the closure so that what we run is reflected at point B.</p><p>To give you an example:</p><pre>CLOSURE <strong>=</strong> proc{puts internal_name}<br><br><strong>class</strong> <strong>Foo</strong><br>  <strong>def</strong> <strong>internal_name</strong><br>    &#39;foo&#39;<br>  <strong>end</strong><br><br>  <strong>def</strong> <strong>closure</strong><br>    proc{puts internal_name}<br>  <strong>end</strong><br><br>  <strong>def</strong> <strong>name1</strong><br>    closure.<strong>call</strong><br>  <strong>end</strong><br><br>  <strong>def</strong> <strong>name2</strong><br>    CLOSURE.<strong>call</strong><br>  <strong>end</strong><br><br><strong>end</strong><br><br>puts Foo.<strong>new</strong>.<strong>name1</strong> <em>#=&gt; foo</em><br>puts Foo.<strong>new</strong>.<strong>name2</strong> <em>#=&gt; undefined local variable or method `internal_name&#39; for main:Object (NameError)</em></pre><p>Makes sense that name2 method failed because internal_name had not been defined when we defined the closure.</p><p>However, it is possible to redefine the proc’s binding (lexical scope) using instance_exec:</p><pre>CLOSURE <strong>=</strong> proc{puts internal_name}<br><br><strong>class</strong> <strong>Foo</strong><br>  <strong>def</strong> <strong>internal_name</strong><br>    &#39;foo&#39;<br>  <strong>end</strong><br><br>  <strong>def</strong> <strong>closure</strong><br>    proc{puts internal_name}<br>  <strong>end</strong><br><br>  <strong>def</strong> <strong>name1</strong><br>    closure.<strong>call</strong><br>  <strong>end</strong><br><br>  <strong>def</strong> <strong>name2</strong><br>    instance_exec(<strong>&amp;</strong>(CLOSURE))<br>  <strong>end</strong><br><br><strong>end</strong><br><br>puts Foo.<strong>new</strong>.<strong>name1</strong> <em>#=&gt; foo</em><br>puts Foo.<strong>new</strong>.<strong>name2</strong> <em>#=&gt; foo</em></pre><p>Success! This means that we can write code in one part of our app and run it under totally different context. But where could this be useful? I have been using it in various hacks but one of most useful ones are in Rails routes. This little trick has helped me to re-map nested routes for free.</p><p>Let’s say that we have the following route:</p><pre>  namespace :api do<br>    namespace :v1 do<br>      resources :company_users, only: [:show] do<br>        resources :posts, only: [:index] do<br>          resource :stats, only: [:show]<br>        end<br>      end<br>    end<br>  end</pre><p>This leads to the following routes:</p><pre>/api/v1/company_users/:id<br>/api/v1/company_users/:company_user_id/posts<br>/api/v1/company_users/:company_user_id/posts/:post_id/stats</pre><p>Turns out that :company_user_id is kind of useless and we would like to give more flexibility to the client by having the following:</p><pre>/api/v1/stats?user_id=:company_user_id&amp;post_id=:post_id</pre><p>However, the API is already out in production and changes are difficult.</p><pre>namespace :api <strong>do</strong><br>    namespace :v1 <strong>do</strong><br>      resources :company_users, only: [:show] <strong>do</strong><br>        resources :posts, only: [:index] <strong>do</strong><br>          resource :stats, only: [:show]<br>        <strong>end</strong><br>      <strong>end</strong><br><br>      resource :stats, only: [:show], defaults: {company_user_id: proc{params[:company_id]}}<br>    <strong>end</strong><br>  <strong>end</strong></pre><p>Params inside routes?! Yes! Because we will rebind the context of that proc in the context of a controller with the following snippet:</p><pre>def reshape_hash!<br>    self.params = HashWithIndifferentAccess.new(params.to_unsafe_h.reshape(self))<br>end</pre><p>Now if you send user_id to this route, it will be added as company_user_id by adding this method as a before_filter</p><pre><strong>class</strong> <strong>Api::</strong>V1<strong>::</strong>StatsController <strong>&lt;</strong> ApplicationController<br>  before_action :authenticate_user!<br>  before_action :reshape_hash!<br><br>  <strong>def</strong> <strong>index</strong><br>    stats <strong>=</strong> Stats.<strong>new</strong>(current_user).<strong>all</strong>(<br>      user_id: params[:company_user_id], post_id: params[:post_id]<br>    )<br><br>    render json: stats, serializer: StatsSerializer<br>  <strong>end</strong></pre><p>I have used it in other places too but mostly as a last resort. Use with care!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e04ce780f5b1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/kollegorna/things-i-learned-developing-ruby-and-rails-apps-over-the-past-3-years-e04ce780f5b1">Things I learned developing Ruby and Rails apps over the past 3+ years</a> was originally published in <a href="https://medium.com/kollegorna">Kollegorna</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rendering Ember components from Rails]]></title>
            <link>https://medium.com/kollegorna/rendering-ember-components-from-rails-ba6cfeea5f79?source=rss-9af304883e1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba6cfeea5f79</guid>
            <category><![CDATA[ember]]></category>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[rendering]]></category>
            <dc:creator><![CDATA[Filippos Vasilakis]]></dc:creator>
            <pubDate>Mon, 23 Jan 2017 00:00:00 GMT</pubDate>
            <atom:updated>2017-10-25T15:08:21.357Z</atom:updated>
            <content:encoded><![CDATA[<p>At Kollegorna we have been working with Ember <em>a lot</em>. Usually we have Rails as a backend serving APIs and treat Ember as a separate project, in its own repo. When deploying Ember, we usually deploy Ember in a separate Heroku instance as well although leting Rails do the deployment of the Ember app through Redis is also possible.</p><p>However, what other options do we have with Ember? Can we have Ember only in a part of our app? Or even is it possible to let Rails <strong>render only specific Ember components</strong> ?</p><p>As we will see both are possible and easy using <a href="https://github.com/thoughtbot/ember-cli-rails">ember-cli-rails</a> and <a href="https://github.com/mitchlloyd/ember-islands">ember-islands</a>.</p><h3>Option 1: Ember being the sole frontend of your Rails app</h3><p>This option is when you want to go all-Ember in your front-end. To achieve that you need to install <a href="https://github.com/thoughtbot/ember-cli-rails">ember-cli-rails</a> and follow the installation in the README. Basically you need to do the following:</p><ul><li>Create an Ember app inside the Rails app: ember new frontend --skip-git</li><li>Make Ember app use pods by adding in config/environment.js: podModulePrefix: &#39;frontend/pods&#39;. Actually this is optional but pods offer greater flexibility.</li><li>Add a hello world inside frontend/app/pods/application/template.hbs. We use the pods structure so parent dirs need to be created if not there.</li></ul><p>Now if you go inside the frontend directory and start the Ember app you should see the hello world text (run node_modles/ember-cli/bin/ember s or just ember s if you have it globally installed). If this doesn&#39;t work it means you have something wrong on the Ember side.</p><p>Note that you can now start working on Ember like you would in any other Ember project. If Rails API endpoints need to run while working on Ember, instead of having 2 separate processes (bundle exec rails s and node_modles/ember-cli/bin/ember s) and specify the server API url/host/namespace in the Ember app, you can pack your Ember app in your Rails app (hot reloading is supported!):</p><ul><li>Run: rails generate ember:init</li><li>Install Ember addon: ember install ember-cli-rails-addon (inside the frontend/ dir)</li><li>Mount Ember app to a route in Rails: mount_ember_app :frontend, to: &quot;/&quot;</li><li>Install Ember dependencies in Rails: bundle exec rake ember:install</li></ul><p>Tada! Now you should be able to run just the Rails server (bundle exec rails s) and see your Ember app live.</p><h3>Option 2: Use Ember app(s) in some part(s) of your Rails app</h3><p>If you already have your Rails views but you want a part of it (say that you develop a /dashboard) to be in Ember then you can follow the same steps as in option 1, only that we need to tell Rails to mount Ember in a different location:</p><ul><li>mount_ember_app :frontend, to: &quot;/dashboard&quot;</li></ul><p>However there are 2 things that you need to configure in the Ember side: * set rootURL: &#39;/dashboard&#39; in the Ember config file * set locationType: &#39;none&#39; also in the Ember config file</p><p>I like the approach of <a href="https://github.com/thoughtbot/ember-cli-rails">ember-cli-rails</a> as it allows the front-end team to work independently from the backend team. <strong>Front-end team can design and implement the app routes, the flow, the HTML/CSS/JS code independently from the backend team and vice versa.</strong> When it makes sense both work using the Rails server which using <a href="https://github.com/thoughtbot/ember-cli-rails">ember-cli-rails</a> packs and serves both codebases in a single one. Note that <strong>you can mount as many Ember apps as you want in the same way</strong>.</p><h3>Option 3: Rendering Ember components from the Rails views</h3><p><a href="https://github.com/mitchlloyd/ember-islands">ember-islands</a> takes it a step further by allowing you to render specific components only. For instance we might don’t want to render the whole dashboard page in Ember but instead only a couple components that are very dynamic in nature (and using jQuery would result in spaghetti code). To achieve that we need to do a couple more things.</p><p>First, we can now remove the Ember mounted app from routes since we will render server-side code which will start Ember manually. We need to tell Rails to include all the Ember JS files in views:</p><ul><li>Add mount_ember_assets :frontend, to: &quot;/&quot; inside routes. Note that we now mount only assets.</li><li>Add &lt;%= include_ember_script_tags :frontend, prepend: &quot;/&quot; %&gt; and &lt;%= include_ember_stylesheet_tags :frontend, prepend: &quot;/&quot; %&gt; in the head section of application layout (or anywhere else you want to have Ember components)</li></ul><p>Then we can continue:</p><ul><li>In Ember config set locationType to none and set rootUrl to root again (&#39;/&#39;)</li><li>Install ember-islands in frontend ember app: ember install ember-islands</li><li>Add {{ember-islands}} in application template. This handles the manual Ember initialization.</li><li>Install new Ember dependencies in Rails: bundle exec rake ember:install (you should run this everytime you change an Ember dependency)</li></ul><p>Go and create the template of a single component that we will use, named user-profile under frontend/app/pods/components/user-profile/template.hbs. The component is supposed to get name and id of the user and display them. Here is an example template:</p><pre>&lt;h3&gt; User Profile &lt;/h3&gt;<br><br><strong>{{</strong>name<strong>}}</strong> (<strong>{{</strong>id<strong>}}</strong>)</pre><p>Now in any view we can render it:</p><pre>&lt;h1&gt; Dashboard &lt;/h1&gt;<br>&lt;div<br>  data-component=&#39;user-profile&#39;<br>  data-attrs=&#39;{&quot;name&quot;: &quot;Sally User&quot;, &quot;id&quot;: &quot;4&quot;}&#39;&gt;<br>&lt;/div&gt;</pre><p>Fire up the Rails server and check your /dashboard url. You should see the HTML generated by the Ember component. If you render such components quite oftenly, you can use a Rails helper for that:</p><pre><strong>def</strong> <strong>ember_component</strong>(tag, name, attrs <strong>=</strong> {})<br>  content_tag(tag, &#39;&#39;, data: {component: name, attrs: attrs.<strong>to_json</strong>})<br><strong>end</strong></pre><p>So our view becomes more beautiful:</p><pre>&lt;h1&gt; Dashboard &lt;/h1&gt;<br><strong>&lt;%=</strong> ember_component(:div, &#39;user-profile&#39;, {name: &#39;Sally User&#39;, id: 4}) <strong>%&gt;</strong></pre><p>We have to watch out what you pass in Ember through the data-attrs and authorize only the allowed attributes (like we would in a regular API). Personally, on models (or any Ruby object) I use an .as_ember_json method which I filter <em>a lot</em> before passing the model to a component.</p><p>I have created an <a href="https://github.com/kollegorna/rails-ember-islands">example app</a> (forked from the <a href="https://bitbucket.org/railstutorial/sample_app_4th_ed">Rails tutorial app</a>) in which I added a new route for users index, only this time I render the users using Ember components.</p><p>Can you spot the difference?</p><p><strong>Note that </strong><a href="https://github.com/mitchlloyd/ember-islands"><strong>ember-islands</strong></a><strong> is backend-agnostic and you can use it with any backend framework (Phoenix, Spring Boot, Laravel, etc).</strong></p><p>Have fun!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba6cfeea5f79" width="1" height="1" alt=""><hr><p><a href="https://medium.com/kollegorna/rendering-ember-components-from-rails-ba6cfeea5f79">Rendering Ember components from Rails</a> was originally published in <a href="https://medium.com/kollegorna">Kollegorna</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[November’s PDDs]]></title>
            <link>https://medium.com/kollegorna/novembers-pdds-ce9de461cf9e?source=rss-9af304883e1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce9de461cf9e</guid>
            <category><![CDATA[personal-development]]></category>
            <category><![CDATA[time]]></category>
            <category><![CDATA[knowledge]]></category>
            <category><![CDATA[investing]]></category>
            <dc:creator><![CDATA[Filippos Vasilakis]]></dc:creator>
            <pubDate>Mon, 28 Nov 2016 00:00:00 GMT</pubDate>
            <atom:updated>2017-10-26T08:15:45.362Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Every sixth week we have Personal Development Days (PDD) here at Kollegorna. This means that everyone is free to work on something on their choice that’s related to our work. The PDD:s starts on Thursday and ends on Monday. So there’s plenty of time to learn pick up new skills, try new technology or just get better at something you already do. You’re free to work by yourself or team up and collaborate with someone else in the team.</em></p><p><em>This is a summary of what happened this time:</em></p><h3>Eduardo</h3><p>The shoemaker’s children always go barefoot, the saying goes. That’s how we’ve felt about our website for quite a while. We spend so much time obsessing over client projects that we’ve often overlooked our own. So, given three days to work on anything, I just bit the bullet and launched myself into a design and development sprint. Three days isn’t enough to do a whole lot, but just the opportunity to start over with a clean slate was compelling enough.</p><p>We’ve been using Middleman for most of the static websites we build, including our own. To take the gruesome work out of setting up a new project, we have an internal <a href="https://github.com/kollegorna/middleman-boilerplate">Middleman boilerplate</a>. We use it as the starting point for all of our Middleman projects, so we’re constantly updating and improving it. By coupling that with our <a href="https://github.com/kollegorna/design-system">design system</a> (which we use to store shared resources, variables and dependencies that we use throughout all of our own websites), I managed to have my development environment set up in, quite literally, a couple of minutes.</p><p>That meant I could use most of my time, during these past three days, to focus on actually building stuff. I didn’t get around to finish all of it, but got surprisingly close. We’re hoping we can have all of the content and missing pages ready before the end of the year, so we can start 2017 with a bang. And when we do, of course, we’ll open source it, just like we did with our <a href="https://github.com/kollegorna/kollegorna.se">current website</a>.</p><h3>Ivan</h3><p>I decided (once again) to take a look at some Swift/iOS courses. I found this one <a href="http://swifteducation.github.io/">http://swifteducation.github.io/</a> and gave it a try. I took 3 of the courses there:</p><ul><li>WordCollage — Demonstrate the basics of Auto Layout and connecting interface views to controller actions.</li><li>UnitConverter — Teach students about delegates, delegation and protocols through the creation of a programming classic. Facilitate a deeper understanding of Model-View-Controller, and demonstrate how to persist data with NSUserDefaults.</li><li>Clock — Dive in with everyone’s essential iOS app: the clock. Teach students about Interface Builder, UILabels, IBOutlets, models, views, controllers, NSTimer and how to handle device orientation.</li></ul><p>After completing those I discovered that <a href="http://84601a65.ngrok.io/blog/2016/11/november-pdd/www.raywenderlich.com">www.raywenderlich.com</a> is offering 50% off Black Friday deals.</p><p>I bought “The iOS Apprentice” and “Core Data by Tutorials”. Currently I’m going through “The iOS Apprentice” and I’m really having fun with that!</p><p>I can honestly recommend that to anybody who’s willing to dive into iOS. I’ll definitely spend some time with it even when our PDDS are over.</p><h3>Bindiya</h3><p>In the recent PDD I learned how to use Photoshop CS6 software and create Facebook posts and ads. Using Photoshop makes editing much more easier and the effects are as good as natural, hence it gives more professional look and feel to the ads created.Also, created a new</p><p>Youtube Channel and learned how to manage Youtube channel and video upload with some edits, sound effects and promotion link &amp; ad integration in the video, along with analytics reports and Search Engine Optimization for Youtube videos. Where you can get the exact reports about each viewer and make analysis based on behavior observed with statistical data.</p><h3>Dennis</h3><p>I finally finished the WesBos ES6 tutorial(https://es6.io). I also checked out React through <a href="https://github.com/verekia/js-stack-from-scratch">https://github.com/verekia/js-stack-from-scratch</a> and also <a href="http://vuejs.org/">Vue.js</a> with the help of their documentation. Next step is to build an app using both frameworks and see what sticks. React have more companies behind it but Vue feels simpler to implement step-by-step(component-by-component).</p><p>Other than Javascript diving I also caught up on some Rails conference talks and some Elm talks. Elm is really interesting but feels too early to jump from Javascript to that right now when there are more people than me to work on it.</p><h3>Raymall</h3><p>As a front-end developer and user interface designer wanna-be the advantages that React Native offers are what bought me; UI components that feels at home on their respective platforms working along with other web development technologies. Like any new framework there is a learning curve but nothing too complex to feel too intimidated to dive into it. I started with a simple app, show a map fullscreen with a button to pin point to the user current location, easy project concept to start to know React Native.</p><h3>Nikolay</h3><h4>The decision</h4><p>Approaching any personal development project requires one crucial step — the decision on what to work on and what to improve in your skill set. This is not to be undermined, in this part of the process you’re exploring what’s out there, what is the current landscape in your field of expertise and what vital part of this landscape is missing for you.</p><p>This time the decision for me was simple — motion. As we have moved towards flatter UI design in the past years and left skeuomorphism behind, the need to make things clear visually for the user is represented mainly by motion &amp; animations. Material design introduced this concept by highlighting how important it is for every part of the design to have a place, even if not in the viewport — “Motion in the world of material design is used to describe spatial relationships, functionality, and intention with beauty and fluidity.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*XOAnxLtFb3r5glRJJly9Cw.gif" /></figure><h4>The process</h4><p>Armed with the knowledge of what I want to work on now opens up the path for more technical research — what tools do I need to start building animated designs, how can I incorporate those designs in live environments, do I need to learn a new app from scratch for this? All of the above are valid questions, and after figuring out what is most compatible with my workflow I decided on dabbling my feet in Principle (http://principleformac.com). This app has allowed me to visualize my interaction ideas almost instantly, after reading a couple of tutorials and importing my concept designs from Sketch I could just do a couple of easy tasks and have a recording of my interaction ready.</p><p>Now the question becomes — why not do this whole thing in-browser, instead of using a prototype in the first place? The answer here is split in two parts — first is client-side, the ability to quickly mockup a design and show how it becomes alive to the client is invaluable in regards to feedback, and secondly the experimentation freedom you have as a designer — being able to move a couple of sliders and change a couple of pixels on the fly and see the changes take effect live opens up your creative thinking more than staring at a black and white text and trying to figure out how to make things smoother only by tinkering with the code in front of you.</p><p>Another opportunity that coincided with the personal development days at Kollegorna was a dribbble meet up that I had the chance to attend. This included a couple of talks on different topics such as motion design (yup, a hot thing right now) and design systems (such as Atomic Design by Brad Frost).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*nehq1R27yEYS4GyKvTZpzA.jpeg" /></figure><h4>The takeaway</h4><p>All in all I feel extremely lucky to be a part of such an agency that values the personal development of it’s members and is against dogma in general. After having the time to look into motion design I come out of it feeling more confident in my skills on that front, not claiming to have become an expert or anything just in a couple of days, but the big takeaway is this — you should never stop developing yourself, this is the best investment you can make, adding this to my skill set may prove to be useful in the future and if not at least I gave it a try and now feel more competent in that field.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*vUHEGtSx0hE9totQzYNvBQ.jpeg" /></figure><h3>Filippos</h3><h4>Official Manuals!</h4><p>On this PDD I managed to work on something I had been looking forward a lot! Create internal manuals about our style and conventions on things like Ruby, Rails and EmberJS. Small things here and there but I feel that if we manage to follow conventions that we all agree upon we will move faster and it will be easier for anyone to jump in a project.</p><p>I also created a super tiny rails introduction for newcomers. It’s been a pain for front-end people to jump in a Rails project for the first time although it should be as easy as 1–2–3. So I hope this will help anyone becoming familiar with Rails faster.</p><h4>And some Crystal..</h4><p>I recently saw Crystal and I thought to give it a try. The language seems to be pretty immature so I didn’t expect much. After all it makes more sense to invest time in Elixir that Crystal since Elixir’s ecosystem gets more and more mature, Phoenix has reached Rails productivity, if not better and learning a new paradigm (functional) isn’t bad at all.</p><p>However, I don’t know why, but Crystal has definitely sparked my interest! Maybe because I see everywhere how fast it is even single threaded and Boehm-Demers-Weiser GC (which they say is slow), maybe because it has types, maybe because it looks like Ruby.</p><p>I created a simple API using <a href="https://github.com/kemalcr/kemal">kemal</a>: it listens for a request coming from our Slack, it reads the params given in Slack and based on those params it reads the reported timesheets from Harvest. After some small data normalization it sends back to Slack a report.</p><p>I have to say that I was surprised how easy was to write code from my Ruby knowledge. Also I spent much less time debugging around like I would do in a normal Ruby app. Seems like compiler adds a lot of safety in your app. If it compiles it will run almost certainly without any issues.</p><p>I will leave you with a code snippet. Try to figure out if it’s Ruby or Crystal code..</p><pre>require &quot;base64&quot;<br>require &quot;kemal&quot;<br>require &quot;http/client&quot;<br>require &quot;json&quot;<br>require &quot;./auto_report_hours/models/slack&quot;<br>require &quot;./auto_report_hours/models/time_entries&quot;<br>require &quot;./auto_report_hours/version&quot;<br><br>SUBDOMAIN <strong>=</strong> ENV[&quot;SUBDOMAIN&quot;]<br>EMAIL <strong>=</strong> ENV[&quot;EMAIL&quot;]<br>PASSWORD <strong>=</strong> ENV[&quot;PASSWORD&quot;]<br>SLACK_TOKEN <strong>=</strong> ENV[&quot;SLACK_TOKEN&quot;]?<br>SLACK_USERNAME <strong>=</strong> ENV[&quot;SLACK_USERNAME&quot;]?<br><br><strong>module</strong> AutoReportHours<br>  before_all <strong>do</strong> <strong>|</strong>env<strong>|</strong><br>    env.<strong>response</strong>.<strong>content_type</strong> <strong>=</strong> &quot;application/json&quot;<br>  <strong>end</strong><br><br>  get &quot;/&quot; <strong>do</strong> <strong>|</strong>env<strong>|</strong><br>    filters <strong>=</strong> FiltersService.<strong>new</strong>(env.<strong>params</strong>.<strong>query</strong>)<br>    <strong>if</strong> filters.<strong>invalid_request?</strong><br>      &quot;INVALID REQUEST&quot;<br>    <strong>else</strong><br>      Slack.<strong>new</strong>(filters.<strong>date</strong>, filters.<strong>response_url</strong>).<strong>report_time</strong><br>    <strong>end</strong><br>  <strong>end</strong><br><strong>end</strong><br><br><strong>class</strong> <strong>FiltersService</strong><br>  <strong>DEFAULT_CHANNEL</strong> <strong>=</strong> ENV[&quot;DEFAULT_SLACK_CHANNEL&quot;]<br><br>  <strong>def</strong> <strong>initialize</strong>(@query : HTTP<strong>::</strong>Params)<br>  <strong>end</strong><br><br>  <strong>def</strong> <strong>date</strong><br>    <strong>return</strong> parse_date(slack_date) <strong>if</strong> slack_request?<br><br>    <strong>return</strong> parse_date(url_date)<br>  <strong>end</strong><br><br>  <strong>def</strong> <strong>response_url</strong><br>    <strong>if</strong> @query[&quot;response_url&quot;]? <strong>&amp;&amp;</strong> slack_request?<br>      <strong>return</strong> @query[&quot;response_url&quot;].<strong>to_s</strong><br>    <strong>else</strong><br>      DEFAULT_CHANNEL<br>    <strong>end</strong><br>  <strong>end</strong><br><br>  <strong>def</strong> <strong>invalid_request?</strong><br>    <strong>return</strong> <strong>true</strong> <strong>if</strong> slack_request? <strong>&amp;&amp;</strong> <strong>!</strong>valid_slack_request?<br><br>    <strong>return</strong> <strong>false</strong><br>  <strong>end</strong><br><br>  <strong>private</strong> <strong>def</strong> <strong>slack_request?</strong><br>    <strong>return</strong> @query[&quot;token&quot;]?<br>  <strong>end</strong><br><br>  <strong>private</strong> <strong>def</strong> <strong>valid_slack_request?</strong><br>    <strong>return</strong> <strong>false</strong> <strong>if</strong> @query[&quot;token&quot;]?.<strong>to_s</strong> <strong>!=</strong> SLACK_TOKEN<br>    <strong>return</strong> <strong>false</strong> <strong>if</strong> @query[&quot;team_domain&quot;]?.<strong>to_s</strong> <strong>!=</strong> SUBDOMAIN<br>    <strong>return</strong> <strong>false</strong> <strong>if</strong> @query[&quot;user_name&quot;]?.<strong>to_s</strong> <strong>!=</strong> SLACK_USERNAME<br><br>    <strong>return</strong> <strong>true</strong><br>  <strong>end</strong><br><br>  <strong>private</strong> <strong>def</strong> <strong>slack_date</strong><br>    @query[&quot;text&quot;]?.<strong>to_s</strong><br>  <strong>end</strong><br><br>  <strong>private</strong> <strong>def</strong> <strong>url_date</strong><br>    @query[&quot;on&quot;]?.<strong>to_s</strong><br>  <strong>end</strong><br><br>  <strong>private</strong> <strong>def</strong> <strong>parse_date</strong>(date_string)<br>    <strong>return</strong> Time.<strong>now</strong> <strong>-</strong> 1.<strong>day</strong> <strong>if</strong> date_string <strong>==</strong> &quot;yesterday&quot;<br>    <strong>begin</strong><br>      <strong>return</strong> Time.<strong>parse</strong>(date_string, &quot;%F&quot;) <strong>if</strong> date_string.<strong>to_s</strong>.<strong>includes?</strong>(&quot;-&quot;)<br>    <strong>rescue</strong> Time<strong>::</strong>Format<strong>::</strong>Error<br>    <strong>end</strong><br><br>    <strong>return</strong> Time.<strong>now</strong><br>  <strong>end</strong><br><strong>end</strong><br><br>Kemal.<strong>run</strong></pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce9de461cf9e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/kollegorna/novembers-pdds-ce9de461cf9e">November’s PDDs</a> was originally published in <a href="https://medium.com/kollegorna">Kollegorna</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lazy loading async relations in Ember]]></title>
            <link>https://medium.com/kollegorna/lazy-loading-async-relations-in-ember-74012f048947?source=rss-9af304883e1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/74012f048947</guid>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[relations]]></category>
            <category><![CDATA[ember]]></category>
            <category><![CDATA[async]]></category>
            <category><![CDATA[tıp]]></category>
            <dc:creator><![CDATA[Filippos Vasilakis]]></dc:creator>
            <pubDate>Mon, 27 Jul 2015 00:00:00 GMT</pubDate>
            <atom:updated>2017-10-25T15:06:42.297Z</atom:updated>
            <content:encoded><![CDATA[<p>In ember models you can define if a relation is async or not by adding {async: true}, after the relation. The point of that option depends on your adapter but in most cases means that your backend returns the ids of the relations instead of embedding them in the initial resource.</p><p>But still, sometimes ember will go and fetch all of them even if you need only one of them.</p><p>For instance the other day I had the following code:</p><pre>{ {#link-to &#39;fault.exception&#39; fault fault.exceptions.firstObject}}<br>  { {fault.eClass}} in { {fault.filepath}}:{ {fault.line}}&lt;br&gt;<br>  { {fault.message}}<br>{ {/link-to}}</pre><p>fault model has many exceptions. I needed only the first exception but ember would send a banch of requests:</p><pre>//model request<br>Started GET &quot;/rack-reqorder/api/v1/faults?per_page=1&amp;sort%5Bupdated_at%5D=desc&quot; for 127.0.0.1 at 2015-07-22 13:06:23 +0300<br><br>//requests generated by the template<br>Started GET &quot;/rack-reqorder/api/v1/exceptions/55ae0bb44d61632688720600&quot; for 127.0.0.1 at 2015-07-22 13:06:24 +0300<br>Started GET &quot;/rack-reqorder/api/v1/exceptions/55ae0bc64d61632688750600&quot; for 127.0.0.1 at 2015-07-22 13:06:24 +0300<br>Started GET &quot;/rack-reqorder/api/v1/exceptions/55ae0bdd4d61632688ec0600&quot; for 127.0.0.1 at 2015-07-22 13:06:24 +0300<br>Started GET &quot;/rack-reqorder/api/v1/exceptions/55ae0c184d61632688430700&quot; for 127.0.0.1 at 2015-07-22 13:06:24 +0300<br>Started GET &quot;/rack-reqorder/api/v1/exceptions/55ae0bf04d61632688150700&quot; for 127.0.0.1 at 2015-07-22 13:06:24 +0300<br>Started GET &quot;/rack-reqorder/api/v1/exceptions/55ae0c014d616326883e0700&quot; for 127.0.0.1 at 2015-07-22 13:06:24 +0300<br>Started GET &quot;/rack-reqorder/api/v1/exceptions/55ae0c214d61632688460700&quot; for 127.0.0.1 at 2015-07-22 13:06:24 +0300<br>Started GET &quot;/rack-reqorder/api/v1/exceptions/55ae0c524d616326884b0700&quot; for 127.0.0.1 at 2015-07-22 13:06:24 +0300<br>Started GET &quot;/rack-reqorder/api/v1/exceptions/55ae0c7c4d616326884e0700&quot; for 127.0.0.1 at 2015-07-22 13:06:24 +0300</pre><p>Ember here sees that you need the has many relation of fault and fetches all the exception ids that were found in the fault resource making the whole app slower.</p><p>How can we mitigate this? It turns out that we can retrieve the exception ids of each fault model. They are hidden under _data.exceptions (actually under _data you can find all data that server returned for that resource). All you need to do is to add a computed property for that and with an Ember enumerator return an array of the ids.</p><pre>exceptions: DS.hasMany(&#39;exception&#39;, {async: <strong>true</strong>}),<br>  exception_ids: <strong>function</strong>() {<br>    <strong>return</strong> <strong>this</strong>.get(&#39;_data.exceptions&#39;).map(<strong>function</strong>(item) { <strong>return</strong> item.id; });<br>  }.property(&#39;exceptions&#39;)</pre><p>Similarly to get the id of a belongsTo relation:</p><pre>fault: DS.belongsTo(&#39;fault&#39;, {async: <strong>true</strong>}),<br>  fault_id: <strong>function</strong>() {<br>    <strong>return</strong> <strong>this</strong>.get(&#39;_data.fault&#39;);<br>  }.property(&#39;fault&#39;),</pre><p>Now using the ember link-to helper with a model id, ember won’t fetch the model until user clicks on it. And even then, ember will fetch only that child model and not all child models for that relation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74012f048947" width="1" height="1" alt=""><hr><p><a href="https://medium.com/kollegorna/lazy-loading-async-relations-in-ember-74012f048947">Lazy loading async relations in Ember</a> was originally published in <a href="https://medium.com/kollegorna">Kollegorna</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>