<?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 Ryan Francis on Medium]]></title>
        <description><![CDATA[Stories by Ryan Francis on Medium]]></description>
        <link>https://medium.com/@ryan_p_francis?source=rss-c2725b33016------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*IFO0zYXeqRg1R6ZCk5FkHQ.jpeg</url>
            <title>Stories by Ryan Francis on Medium</title>
            <link>https://medium.com/@ryan_p_francis?source=rss-c2725b33016------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 01:18:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ryan_p_francis/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[Simple Gem to Create a Rails CSV Export]]></title>
            <link>https://medium.com/@ryan_p_francis/simple-gem-to-create-a-rails-csv-export-a803c2a19b32?source=rss-c2725b33016------2</link>
            <guid isPermaLink="false">https://medium.com/p/a803c2a19b32</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <dc:creator><![CDATA[Ryan Francis]]></dc:creator>
            <pubDate>Sat, 24 Jun 2017 01:04:33 GMT</pubDate>
            <atom:updated>2017-06-24T01:04:33.614Z</atom:updated>
            <content:encoded><![CDATA[<h4>How many times have we all created the same CSV export feature? It’s time to simplify.</h4><p>After implementing CSV exporting in over 10 Rails apps, I finally decided enough is enough and created a gem.</p><p>Full disclosure, this gem is in its very early stages, but would love feedback from the Rails community!</p><h4>How it Works</h4><p>1. Install gem:</p><pre>gem &#39;lp_csv_exportable&#39;</pre><p>2. Create a class like below:</p><pre>class ExportUsers<br>  include LpCSVExportable::CanExportAsCSV</pre><pre>  column &#39;First Name&#39;, model_method: :first_name<br>  column &#39;Last Name&#39;, model_method: :last_name<br>  column &#39;Email&#39;, model_method: :email<br>  column &#39;Role&#39;, model_methods: %i[membership name]<br>end</pre><p>3. Use the class in your controller:</p><pre>def index<br>  respond_to do |format|<br>    format.csv do<br>      export = ExportUsers.new<br>      export.collection = User.all<br>      send_data export.to_csv<br>    end<br>  end<br>end</pre><p><strong>Comments &amp; Feedback Welcome! </strong>Gem is here: <a href="https://github.com/launchpadlab/lp_csv_exportable">https://github.com/launchpadlab/lp_csv_exportable</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a803c2a19b32" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Say No to If/Else Statements]]></title>
            <link>https://medium.com/launchpad-lab/say-no-to-if-else-statements-ad841ddfa3dc?source=rss-c2725b33016------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad841ddfa3dc</guid>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[ruby]]></category>
            <dc:creator><![CDATA[Ryan Francis]]></dc:creator>
            <pubDate>Tue, 23 May 2017 23:55:28 GMT</pubDate>
            <atom:updated>2017-05-23T23:55:28.041Z</atom:updated>
            <content:encoded><![CDATA[<p>One of the first lessons we learn in programming is how to write a conditional. If/Else statements seem so central to programming that it is hard to imagine a world without them.</p><p>Over the last year, I have made it my goal to minimize my usage of If/Else. I have found that it is actually quite easy and results in code that is much easier to read and maintain.</p><h3>Example If/Else Statement</h3><pre>def run<br>  water_temperature = Water.get_last_temperature</pre><pre>  if water_temperature &gt; 100.0<br>    Timer.start(end_in: 8.minutes)<br>  else<br>    temperature_left = 100.0 — water_temperature<br>    time_left_in_minutes = (temperature_left / TEMP_INCREASE_PER_MINUTE)<br>    send_message(“Minutes remaining: #{time_left_in_minutes}”)<br>  end<br>end</pre><p>I hope you’re confused — I know I would be if this was the first time I read that method.</p><p>Here are a few questions that may have popped up as you read that method:</p><p>- Why are we checking that the water_temperature exceeds 100.0? What is special about 100.0?<br>- Why do we start a timer and set the timer to 8 minutes when temperature exceeds 100.0?<br>- What is happening in the second branch of this conditional and why is it implemented?</p><h3>Quick Refactoring</h3><p>Now, let’s rewrite this same If/Else statement but with the following changes:</p><p>1. Each branch of the conditional becomes a method<br>2. The conditional check itself (water_temperature &gt; 100.0) becomes a method</p><pre>def run<br>  if boiling?<br>    set_timer_for_pasta<br>  else<br>    show_time_until_boiling<br>  end<br>end</pre><pre>private</pre><pre>def water_temperature<br>  Water.get_last_temperature<br>end</pre><pre>def boiling?<br>  water_temperature &gt;= 100.0<br>end</pre><pre>def set_timer_for_pasta<br>  Timer.start(end_in: 8.minutes)<br>end</pre><pre>def show_time_until_boiling<br>  temperature_left = 100.0 - water_temperature<br>  time_left_in_minutes = (temperature_left / TEMP_INCREASE_PER_MINUTE)<br>  send_message(&quot;Minutes remaining: #{time_left_in_minutes}&quot;)<br>end</pre><p>With the simplified If/Else statement, we can now convert it to a ternary operator:</p><pre>def run<br>  boiling? ? set_timer_for_pasta : show_time_until_boiling<br>end</pre><pre>private</pre><pre># ...</pre><h3>Results</h3><p>With this refactoring, a seemingly complicated if/else statement just became a dead simple ternary operation. Any programmer can understand this:</p><pre>boiling? ? set_timer_for_pasta : show_time_until_boiling</pre><p>Furthermore, our confusions earlier are now obvious:</p><p><strong>- Why are we checking that the water_temperature exceeds 100.0? What is special about 100.0?</strong></p><p>Answer: It is checking to see if the water is boiling (100.0 must be Celsius temperature by this logic)</p><p><strong>- Why do we start a timer and set the timer to 8 minutes when temperature exceeds 100.0?</strong></p><p>Answer: Water is boiling so it is time to start cooking some pasta and we don’t want to overcook it!</p><p><strong>- What is happening in the second branch of this conditional and why is it implemented?</strong></p><p>Answer: When the water is not boiling, we simply want to show how much time is left until the water will boil.</p><h3>Small Methods, Big Documentation</h3><p>The beauty of small methods is that they serve as wonderful little journalists, documenting their purpose to the world. If/Else statements are complicated because there are three components that often lack documentation: (1) the conditional, (2) the first branch, and (3) the second branch.</p><p>By simply breaking each of these components into small methods it allows us to drop the If/Else into a ternary every time, improving the readability of the logic itself while bolstering the documentation attached to the three components of the conditional.</p><h3>One Simple Technique to Solve Complex Problems</h3><p>The next time you spot an if/else statement, just move each branch and the conditional logic itself into separate methods and create a nice ternary operator. As you follow this pattern over time, your code will become much easier to digest and will naturally document itself.</p><p><em>Originally posted at </em><a href="https://launchpadlab.com/blog/say-no-to-if-else"><em>launchpadlab.com</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad841ddfa3dc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/launchpad-lab/say-no-to-if-else-statements-ad841ddfa3dc">Say No to If/Else Statements</a> was originally published in <a href="https://medium.com/launchpad-lab">LaunchPad Lab</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Say No to If/Else Statements]]></title>
            <link>https://medium.com/@ryan_p_francis/say-no-to-if-else-statements-eb389f75b13f?source=rss-c2725b33016------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb389f75b13f</guid>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Ryan Francis]]></dc:creator>
            <pubDate>Sat, 20 May 2017 00:50:35 GMT</pubDate>
            <atom:updated>2017-05-20T00:50:35.242Z</atom:updated>
            <content:encoded><![CDATA[<p>One of the first lessons we learn in programming is how to write a conditional. If/Else statements seem so central to programming that it is hard to imagine a world without them.</p><p>Over the last year, I have made it my goal to minimize my usage of If/Else. I have found that it is actually quite easy and results in code that is much easier to read and maintain.</p><h3>Example If/Else Statement</h3><pre>def run<br>  water_temperature = Water.get_last_temperature</pre><pre>if water_temperature &gt; 100.0<br>    Timer.start(end_in: 8.minutes)<br>  else<br>    temperature_left = 100.0 — water_temperature<br>    time_left_in_minutes = (temperature_left / TEMP_INCREASE_PER_MINUTE)<br>    send_message(“Minutes remaining: #{time_left_in_minutes}”)<br>  end<br>end</pre><p>I hope you’re confused — I know I would be if this was the first time I read that method.</p><p>Here are a few questions that may have popped up as you read that method:</p><blockquote>- Why are we checking that the water_temperature exceeds 100.0? What is special about 100.0?<br>- Why do we start a timer and set the timer to 8 minutes when temperature exceeds 100.0?<br>- What is happening in the second branch of this conditional and why is it implemented?</blockquote><h3>Quick Refactoring</h3><p>Now, let’s rewrite this same If/Else statement but with the following changes:</p><p>1. Each branch of the conditional becomes a method<br>2. The conditional check itself (water_temperature &gt; 100.0) becomes a method</p><pre>def run<br>  if boiling?<br>    set_timer_for_pasta<br>  else<br>    show_time_until_boiling<br>  end<br>end</pre><pre>private</pre><pre>def water_temperature<br>  Water.get_last_temperature<br>end</pre><pre>def boiling?<br>  water_temperature &gt;= 100.0<br>end</pre><pre>def set_timer_for_pasta<br>  Timer.start(end_in: 8.minutes)<br>end</pre><pre>def show_time_until_boiling<br>  temperature_left = 100.0 - water_temperature<br>  time_left_in_minutes = (temperature_left / TEMP_INCREASE_PER_MINUTE)<br>  send_message(&quot;Minutes remaining: #{time_left_in_minutes}&quot;)<br>end</pre><p>With the simplified If/Else statement, we can now convert it to a ternary operator:</p><pre>def run<br>  boiling? ? set_timer_for_pasta : show_time_until_boiling<br>end</pre><pre>private</pre><pre># ...</pre><h3>Results</h3><p>With this refactoring, a seemingly complicated if/else statement just became a dead simple ternary operation. Any programmer can understand this:</p><pre>boiling? ? set_timer_for_pasta : show_time_until_boiling</pre><p>Furthermore, our confusions earlier are now obvious:</p><p><strong>- Why are we checking that the water_temperature exceeds 100.0? What is special about 100.0?</strong></p><p>Answer: It is checking to see if the water is boiling (100.0 must be Celsius temperature by this logic)</p><p><strong>- Why do we start a timer and set the timer to 8 minutes when temperature exceeds 100.0?</strong></p><p>Answer: Water is boiling so it is time to start cooking some pasta and we don’t want to overcook it!</p><p><strong>- What is happening in the second branch of this conditional and why is it implemented?</strong></p><p>Answer: When the water is not boiling, we simply want to show how much time is left until the water will boil.</p><h3>Small Methods, Big Documentation</h3><p>The beauty of small methods is that they serve as wonderful little journalists, documenting their purpose to the world. If/Else statements are complicated because there are three components that often lack documentation: (1) the conditional, (2) the first branch, and (3) the second branch.</p><p>By simply breaking each of these components into small methods it allows us to drop the If/Else into a ternary every time, improving the readability of the logic itself while bolstering the documentation attached to the three components of the conditional.</p><h3>One Simple Technique to Solve Complex Problems</h3><p>The next time you spot an if/else statement, just move each branch and the conditional logic itself into separate methods and create a nice ternary operator. As you follow this pattern over time, your code will become much easier to digest and will naturally document itself.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb389f75b13f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Business Owners Should Care About Code Quality]]></title>
            <link>https://medium.com/@ryan_p_francis/why-business-owners-should-care-about-code-quality-9cbe8cea7673?source=rss-c2725b33016------2</link>
            <guid isPermaLink="false">https://medium.com/p/9cbe8cea7673</guid>
            <category><![CDATA[business]]></category>
            <category><![CDATA[code-quality]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[entrepreneurship]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Ryan Francis]]></dc:creator>
            <pubDate>Fri, 17 Feb 2017 19:55:28 GMT</pubDate>
            <atom:updated>2017-02-17T19:55:28.410Z</atom:updated>
            <content:encoded><![CDATA[<p>Code, while often invisible to the business owner, is the core component to a software product. It literally instructs the software how to behave. Unfortunately, many business owners don’t really understand why or what code quality means to their business.</p><p>The reality is that code quality can be critical to a business’ success. Good code means developers are able to build and change features quicker, and the risk of bugs arising from these changes are lower.</p><p><strong>Good Code = Changeable</strong></p><p><strong>Bad Code = Concrete</strong></p><p>Many business owners think high quality code is for established companies with high budgets. In fact, the inverse is true.</p><p>The younger the software company, the more important code quality is to its success. This is because there is more uncertainty in the business itself, which often means the software will need to evolve quickly to keep up with the shifting foundation beneath it.</p><p>With high quality code, developers can make feature changes like a skiier cutting back and forth down moguls on a black diamond. Left, right, hop over that one, and boom — you just won the race.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*OxUhK3v5WR76QwBj0EVHww.gif" /></figure><p>With low quality code, it looks a little bit more like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*U2uWA5XleJDxJlR6K-W-9g.gif" /></figure><h3>So, what exactly is “Code Quality”?</h3><p>You can think of high quality code as a <strong>well-written story</strong>. The reader of this story is a future developer that is hoping to change it. The better the story, the easier it is for this developer to pick up on the narrative and move it forward.</p><p>If good code is like good writing, than the question is: what makes one piece of writing better than another?</p><p>Here are a few ideas:</p><ul><li>Good writing is easy to read</li><li>Good writing is logical</li><li>Good writing is grammatically correct</li><li>Good writing is succinct (i.e. doesn’t unnecessarily repeat itself)</li><li>Good writing tells a full story</li></ul><p>With these attributes in mind, which of the below pieces of code do you think is better written?</p><p><strong>Option #1:</strong></p><pre>x = 50 / 100<br>print x</pre><p><strong>Option #2:</strong></p><pre>number_of_questions = 100<br>number_correct = 50</pre><pre>test_grade = number_correct / number_questions<br>print test_grade</pre><p>While the first option is much shorter, it does a terrible job at telling a story. What is <em>50</em>? What is <em>100</em>? Why are we dividing them? These are questions that as a reader of the code I would immediately begin to ask.</p><p>In the second option, I know exactly what is happening. We are calculating the grade for some type of test. There are 100 questions on this test and there are only 50 correct answers, so the person got a 50% grade. While longer, this option is much better as it tells a full story about why the code was written in the first place: to calculate the test grade.</p><p>Now picture the difference between these two bits of code being compounded across an application with thousands of lines of code. If all of the code is written like the first option, it takes days to make changes to the application because one must figure out what the code is doing in the first place. What is <em>50</em> and why did we need that again?</p><p>To an untrained eye, the first option may appear to have good code quality. Wow — look how succinct that first bit of code is! Only one line baby! But a veteran is not fooled — this code is not telling a story and the business owner who paid for this line of code will have to pay for this story to be rewritten some day in a manner in which other developers can actually read and understand.</p><h3>How can I make sure I have good code quality?</h3><h4>Test Your Developers’ Writing Skills</h4><p>The first check is to make sure the developers you are hiring are good writers. This sounds funny but it’s honestly a great first check. Have them explain (in writing) something technical and see how easy it is for you to understand. For example, ask “What is Ruby on Rails and why are we (or are we not) using that for our project?”</p><p>If the answer is over your head, it’s not because you’re an idiot, it’s because the developer either doesn’t have a good grasp on what they’re trying to explain or they just plain aren’t good at writing. Either way, this will manifest itself in your application in the form of convoluted, hard to read code. Steer clear.</p><h4>Grade the Code</h4><p>There are some tools that can give you a high-level pulse of your code quality.</p><p>The tool we use at LaunchPad Lab for this is called <a href="http://codeclimate.com/"><strong>Code Climate</strong></a>. It integrates with Github so it takes all of 30 seconds to set it up. Once setup, Code Climate will grade your code on a 4.0 scale.</p><p>If you are thinking about building a new piece of software, start out with Code Climate right out of the gate. There is nothing stopping business owners from having access and being privy to the code quality metrics offered by tools like Code Climate — so take advantage.</p><h4>Setup Continuous Integration</h4><p>Make sure your development team sets up continuous integration. This will encourage them to write the code with tests, which are a big contributor to code quality. It also just makes it a lot easier to make quick iterations on the code base. We recommend <a href="http://codeship.com/"><strong>Codeship </strong></a>for this.</p><h4>Steer Clear of Offshore Developers</h4><p>This is a guideline, not a blanket statement. But in my experience I have seen far more horror stories than successes when hiring overseas. Many of our clients have first hired overseas only to have to scrap the whole application and start over with a US based team.</p><h3>Conclusion</h3><p>Although invisible to the naked eye, Code Quality can deliver a huge ROI, especially for companies that are rapidly changing. Make sure to hire developers that want to write an eloquent story for future developers to read. And use tools like Code Climate to keep a pulse on your Code Quality score.</p><p><em>Originally published at </em><a href="https://launchpadlab.com/blog/why-business-owners-should-care-about-code-quality"><em>launchpadlab.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9cbe8cea7673" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Decorators Saved My Rails App]]></title>
            <link>https://medium.com/@ryan_p_francis/how-decorators-saved-my-rails-app-c5cc18ef7d2e?source=rss-c2725b33016------2</link>
            <guid isPermaLink="false">https://medium.com/p/c5cc18ef7d2e</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <dc:creator><![CDATA[Ryan Francis]]></dc:creator>
            <pubDate>Mon, 08 Aug 2016 16:34:00 GMT</pubDate>
            <atom:updated>2016-08-08T16:37:17.775Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>The Rails app I am building is in the finance sector and as a result has lots of currencies and percentages. The challenge is that the database stores these values as floats (i.e. decimals) and as a result I need to convert these raw values into something presentable on the frontend.</p><p>For example, a currency value in the database of 50.12 becomes $50 when presented to the user in the HTML. Similarly, the percentage value of 0.0508 becomes 5.1% when presented to the user on the frontend.</p><h3>The Wrong Solution</h3><p>In my days as a novice, I would perform this conversion right in the view like so:</p><p>app/views/companies/show.html.erb:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7f3a991a649641f203da78a2eb8ab698/href">https://medium.com/media/7f3a991a649641f203da78a2eb8ab698/href</a></iframe><p>Which produces:</p><pre>Budget: $12,000<br>Actual: $11,485<br>Percent Spent: 5.1%</pre><p>While this solves the problem, it is a poor solution. Anytime I want to display any of these three values on the page, I’ll need to duplicate the formatting logic, including each data’s:</p><ul><li>Format type (currency or percentage)</li><li>Precision (number of decimals)</li><li>Transformation Logic (percentages need to be multiplied by 100)</li></ul><p>When my client calls up and says “Let’s display all percentages in the application as 2 decimal places” (by the way this actually happened), I would need to find all the places in my app using the number_to_percentage helper method and adjust the precision.</p><h3>A Better Solution: Decorators</h3><h4>Code With Me</h4><p>If you’re like me, learning is best accomplished through actually writing code. I’ve setup a basic Rails app for you to code alongside me. Just fork it and clone it down: <a href="https://github.com/francirp/decorator_app">https://github.com/francirp/decorator_app</a></p><pre>bundle<br>bundle exec rake db:create db:migrate</pre><h4>Draper</h4><p>Nowadays I use a gem called <a href="https://github.com/drapergem/draper">Draper</a> so that I don’t have to put these helper methods all throughout my views. Here’s how it works:</p><p>Gemfile:</p><pre>gem &#39;draper&#39;</pre><p>Terminal:</p><pre>bundle<br>rails g decorator Company</pre><p>This generates the company decorator file, which we update to include <strong>budget</strong>, <strong>actual</strong>, and <strong>percent_budget_spent</strong> methods:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/06fc781a93d10c66d8e8b49ae235f2bd/href">https://medium.com/media/06fc781a93d10c66d8e8b49ae235f2bd/href</a></iframe><p>The last step is to “decorate” our ActiveRecord object. Find companies_helper.rb and change it like so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/42210e4bffe3f940e034cefaf50b3597/href">https://medium.com/media/42210e4bffe3f940e034cefaf50b3597/href</a></iframe><pre>Now instead of referencing @company in our views, we simply call company to get the decorated company.</pre><p>Change app/views/companies/show.html.erb to look like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/60faf205125e00fb26cc805c684d2eaa/href">https://medium.com/media/60faf205125e00fb26cc805c684d2eaa/href</a></iframe><p>Which turns into…</p><pre>Budget: $12,000<br>Actual: $11,485<br>Percent Spent: 5.1%</pre><p>Voila! This is a much cleaner and scalable approach. If we ever need to use <strong>budget</strong>, <strong>actual</strong>, or <strong>percent_budget_spent</strong> elsewhere on the page, we can do so without duplicating the helper method.</p><p>However, we run into trouble when we go to create our first form…</p><h4>Forms Trouble</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/905a3e06d8e6751def4e1a1ca61cfd37/href">https://medium.com/media/905a3e06d8e6751def4e1a1ca61cfd37/href</a></iframe><p>I want the <strong>budget</strong> field to look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/1*E_xkDL0YMyelQym7gxTwcg.png" /></figure><p>But it actually looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/448/1*U7lv1wfn4zLdwvgUXiDtFw.png" /></figure><p>Do you see the dollar sign sitting inside the text field? This will pose a problem when we submit the form, as Rails will try to convert $15,000 to a float which results in nil. So why is it there?</p><p>Simple Form, like form_for, looks for a method on our object called <strong>budget</strong>. Since company is actually a CompanyDecorator object, it calls the <strong>budget</strong> method that was defined there first (if it doesn’t find that method on the decorator, then it goes on to call the method on the ActiveRecord object).</p><p>Remember, we did define a <strong>budget</strong> method on the decorator:</p><pre>def budget<br>  h.number_to_currency(object.budget, precision: 0)<br>end</pre><p>So our form is calling this method which is returning a currency formatted string. Unfortunately, this is not what we want.</p><p>As it turns out, we don’t always want to format <strong>budget</strong> as a currency. In this case of the form field, we want to format it as a decimal.</p><p>My solution to this is to use two decorator methods for each column that needs formatted. So for budget we have a <strong>budget</strong> method that returns a formatted decimal and a <strong>display_budget</strong> method that returns a formatted currency.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/57bff34809963af846fb528993e383d7/href">https://medium.com/media/57bff34809963af846fb528993e383d7/href</a></iframe><p>This allows me to use the following methods and receive the following corresponding outputs:</p><pre>&lt;%= company.budget %&gt; =&gt; 1200.00<br>&lt;%= company.display_budget %&gt; =&gt; $1,200</pre><pre>&lt;%= company.actual %&gt; =&gt; 1000.00<br>&lt;%= company.display_actual %&gt; =&gt; $1,000</pre><pre>&lt;%= company.percent_budget_spent %&gt; =&gt; 5.1<br>&lt;%= company.display_percent_budget_spent %&gt; =&gt; 5.1%</pre><p>Simple Form will use the <strong>budget</strong> method, and will therefore be formatted with the <strong>number_with_precision</strong> helper method. Everywhere else in our views we can use <strong>company.display_budget</strong> to render out the currency value.</p><p>Now we update app/views/companies/show.html.erb:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ccdceda0fddeb755a888e220e772695e/href">https://medium.com/media/ccdceda0fddeb755a888e220e772695e/href</a></iframe><p>Which produces:</p><pre>Budget: $12,000<br>Actual: $11,485<br>Percent Spent: 5.1%</pre><p>While I find this to be quite effective, it is cumbersome to write two decorator methods for every currency or percentage field in our application.</p><h3>The Best Solution: Base Decorator</h3><p>Often times the way we format data like currencies and percentages is consistent across the application. Because of this, it would be great to be able to write our decorator like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/16bc68259945dc3c88a19dd5a9f421dc/href">https://medium.com/media/16bc68259945dc3c88a19dd5a9f421dc/href</a></iframe><p>Which should expose the following methods:</p><pre>&lt;%= company.budget %&gt; =&gt; 1200.00<br>&lt;%= company.display_budget %&gt; =&gt; $1,200</pre><pre>&lt;%= company.actual %&gt; =&gt; 1000.00<br>&lt;%= company.display_actual %&gt; =&gt; $1,000</pre><pre>&lt;%= company.percent_budget_spent %&gt; =&gt; 5.1<br>&lt;%= company.display_actual %&gt; =&gt; 5.1%</pre><p>Looks pretty cool, you say. But how?</p><h4>Step 1: Create the Base Decorator</h4><p>Create a Base Decorator file that all of our decorators will inherit from:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8349e463d60501a6dd4b90aa959ca4af/href">https://medium.com/media/8349e463d60501a6dd4b90aa959ca4af/href</a></iframe><p>And inherit from it…</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b2a4c5001834350d8d8a85d37f368487/href">https://medium.com/media/b2a4c5001834350d8d8a85d37f368487/href</a></iframe><h4>Step 2: Create the Currency Method</h4><p>The goal is for the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c23679566ccbb4e117437209e3de3175/href">https://medium.com/media/c23679566ccbb4e117437209e3de3175/href</a></iframe><p>To end up producing something like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8b6c6a6139e5d08ea92b5f64783849e2/href">https://medium.com/media/8b6c6a6139e5d08ea92b5f64783849e2/href</a></iframe><p>With that in mind, let’s take a stab at implementing some meta programming to solve this.</p><p>Start by defining a class method <strong>currency</strong> on our <em>BaseDecorator</em>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/74365cc821ccbd61ccc9d66def7f95f2/href">https://medium.com/media/74365cc821ccbd61ccc9d66def7f95f2/href</a></iframe><p>*keys will end up being an array of keys:</p><pre>[:budget, :actual]</pre><p>So what we want to do is iterate over each of these keys and define two methods, the first which is just the name of the key and returns a decimal format, and the second which prepends <strong>display_</strong> to the name of the key and is a currency format:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7668cc530e2619a2135819157eac5206/href">https://medium.com/media/7668cc530e2619a2135819157eac5206/href</a></iframe><p>In the first define_method block, we want to implement something like:</p><pre>h.number_with_precision(object.budget, precision: 2)</pre><p>While the second should look like:</p><pre>h.number_to_currency(object.budget, precision: 0)</pre><p>However, since the key is a variable, we’ll need to use the send method:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/68342f867ec106e5ede729d84c5fbd58/href">https://medium.com/media/68342f867ec106e5ede729d84c5fbd58/href</a></iframe><p>Now in our CompanyDecorator, let’s call the newly added <strong>currency</strong> method:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/feca85e99eef211f5b1e2c9cd30895d8/href">https://medium.com/media/feca85e99eef211f5b1e2c9cd30895d8/href</a></iframe><p>With that, the following methods produce these results:</p><pre>&lt;%= company.budget %&gt; =&gt; 1200.00<br>&lt;%= company.display_budget %&gt; =&gt; $1,200</pre><pre>&lt;%= company.actual %&gt; =&gt; 1000.00<br>&lt;%= company.display_actual %&gt; =&gt; $1,000</pre><p>Perfect.</p><p>Now only one more step: the percent method.</p><h4>Step 3: Implement the Percent Method</h4><p>I encourage you to try to implement this method on your own. The goal is that you come away with a pattern you can use in your Rails application. Likely your formatting rules and preferences will be different, so understanding how to create these <em>BaseDecorator</em> methods is important.</p><p>In case you get stuck, here is the solution I came up with, which of course goes into the <em>BaseDecorator</em> file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/917f105211cffa44b7bc6432a8f177f5/href">https://medium.com/media/917f105211cffa44b7bc6432a8f177f5/href</a></iframe><p>And finally, we call the percent method from our <em>CompanyDecorator</em>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/16bc68259945dc3c88a19dd5a9f421dc/href">https://medium.com/media/16bc68259945dc3c88a19dd5a9f421dc/href</a></iframe><p>Alas, the above code allows the following to work:</p><pre>&lt;%= company.budget %&gt; =&gt; 1200.00<br>&lt;%= company.display_budget %&gt; =&gt; $1,200</pre><pre>&lt;%= company.actual %&gt; =&gt; 1000.00<br>&lt;%= company.display_actual %&gt; =&gt; $1,000</pre><pre>&lt;%= company.percent_budget_spent %&gt; =&gt; 5.1<br>&lt;%= company.display_actual %&gt; =&gt; 5.1%</pre><p>So what do you think of this approach? I would love to hear your thoughts, criticisms, and ideas.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5cc18ef7d2e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Missing Step in Rails Controllers]]></title>
            <link>https://medium.com/launchpad-lab/the-missing-step-in-rails-controllers-82aaa9172165?source=rss-c2725b33016------2</link>
            <guid isPermaLink="false">https://medium.com/p/82aaa9172165</guid>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[popular]]></category>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <dc:creator><![CDATA[Ryan Francis]]></dc:creator>
            <pubDate>Fri, 26 Feb 2016 16:07:04 GMT</pubDate>
            <atom:updated>2017-01-06T04:36:08.983Z</atom:updated>
            <content:encoded><![CDATA[<h4>Controller Complexity</h4><p>The Rails controller is a precarious place. It acts as the translator between the backend and the frontend, and it is the first place where code seems to gather in complexity. At first we learned that “fat models” was the solution — just push your complex logic down to the model layer. After some time, folks realized that this approach resulted in extremely large ActiveRecord objects that were very difficult — dare I say impossible — to manage over time. So a new solution was needed; namely the Service Object.</p><h4>Service Object to the Rescue?</h4><p>The Service Object promised to not only take logic out of our controllers, but our models too. It would be responsible for performing actions like registering a user, collecting a payment, or filtering search results. The majority of the time, the Service Object was called upon when a form was submitted and some complex backend logic was needed to handle the request. While certainly a great addition to most Rails apps, the service object by itself is ill-equipped to handle all of our form processing needs.</p><h4>The Missing Step in Rails Controllers: Data Transformation</h4><p>In my opinion, our controllers are missing a data transformation step. This is the step where we take our incoming data and transform it into a format our backend can consume. We actually often perform data transformation when we respond to requests with JSON by using tools like Active Model Serializers and Jbuilder. But all of these tools are useful for <strong>outbound data transformation</strong>, not inbound. Just as we need to transform our backend <strong>outbound</strong> data into a format that our frontends can consume (using ASM / Jbuilder), we need to also transform our frontend <strong>inbound</strong> data into a format our backends can consume.</p><h3>Decanter</h3><p>Decanter is a Rails gem created by <a href="http://launchpadlab.com/">LaunchPad Lab</a> that makes it easy to transform incoming data before it hits the model. The basic idea is that form data entered by a user often needs to be processed before it is stored in the database. A typical example of this is a datepicker. A user selects January 15th, 2015 as the date, but this is going to come into our controller as a string like “01/15/2015”, so we need to convert this string into a Ruby Date object before it is stored in our database. Many developers perform this conversion right in the controller, which results in errors and unnecessary complexity, especially as the application grows.</p><h4>Basic Example</h4><p>Take, for example, the following create action for a “Trip” resource:</p><pre>class TripsController &lt; ApplicationController<br>  def create<br>    @trip = Trip.new(trip_params)<br>    start_date = Date.strptime(trip_params[:start_date], &#39;%m/%d/%Y&#39;)<br>    end_date = Date.strptime(trip_params[:end_date], &#39;%m/%d/%Y&#39;)<br>    @trip.start_date = start_date<br>    @trip.end_date = end_date<br><br>    if @trip.save<br>      redirect_to trips_path<br>    elsee<br>      render &#39;new&#39;<br>    end<br>  end<br><br>    private<br><br>      def trip_params<br>        params.require(:trip).permit(:start_date, :end_date)<br>      end<br>  end<br>end</pre><p>Since the trip has a start_date and an end_date, we need to parse these dates before we can save the trip. At first glance, parsing these dates isn’t the end of the world. But as our application grows and we have more “one-off” parsing needs, this approach breaks down.</p><h4>Nested Form Example</h4><p>For example, what happens if the trip now has destinations which each have dates that need parsed too? We would be forced to implement something like:</p><pre>class TripsController &lt; ApplicationController<br>  def create<br>    @trip = Trip.new(trip_params)<br>    start_date = Date.strptime(trip_params[:start_date], &#39;%m/%d/%Y&#39;)<br>    end_date = Date.strptime(trip_params[:end_date], &#39;%m/%d/%Y&#39;)<br>    @trip.start_date = start_date<br>    @trip.end_date = end_date<br><br>    @trip.destinations.each_with_index do |dest, index|<br>      args = trip_params[:destinations_attributes][&quot;#{index}&quot;]<br>      arrival_date = args[:arrival_date]<br>      dep_date = args[:departure_date]<br>      dest.arrival_date = Date.strptime(arrival_date, &#39;%m/%d/%Y&#39;)<br>      dest.departure_date = Date.strptime(dep_date, &#39;%m/%d/%Y&#39;)<br>    end<br><br>    if @trip.save<br>      redirect_to trips_path<br>    else<br>      render &#39;new&#39;<br>    end<br>  end<br><br>    private<br><br>      def trip_params<br>        params.require(:trip).permit(:start_date, :end_date)<br>      end<br>  end<br>end</pre><p>Yikes, this create action is starting to get out of control. Just to parse the trip and destinations’ dates, we need to write all of this code!</p><h4>Decanter to the Rescue</h4><p>A better solution is to send our trip_params through a transformer layer that converts the incoming form data into something our system can handle. Let’s try this with Decanter.</p><p>Install the gem:</p><pre>gem &quot;decanter&quot;</pre><pre>bundle</pre><p>Now generate your Trip and Destination Decanters:</p><pre>rails g decanter Trip start_date:date end_date:date destinations:has_many</pre><pre>rails g decanter Destination city state arrival_date:date departure_date:date</pre><p>Which produces app/decanters/trip_decanter.rb and app/decanters/destination_decanter.rb:</p><pre>class TripDecanter &lt; Decanter::Base<br>  input :start_date, :date<br>  input :end_date, :date<br>  has_many :destinations<br>end</pre><pre>class DestinationDecanter &lt; Decanter::Base<br>  input :city, :string<br>  input :state, :string<br>  input :arrival_date, :date<br>  input :departure_date, :date<br>end</pre><p>Now in our trips_controller:</p><pre>class TripsController &lt; ApplicationController<br>  def create<br>    @trip = Trip.decant_new(trip_params)<br><br>    if @trip.save<br>      redirect_to trips_path<br>    else<br>      render &#39;new&#39;<br>    end<br>  end<br><br>  private<br><br>    def trip_params<br>      params.require(:trip).permit(:start_date, :end_date)<br>    end<br>end</pre><p>I don’t know about you, but I like when my controller actions look like the above example. It’s just boilerplate Rails code that any developer can understand.</p><h4>Default and Custom Parsers</h4><p>With these decanters in place, we can handle all kinds of data transformation in one easy to manage place. Here are some of the parsers Decanter provides out-of-the-box</p><ul><li>boolean</li><li>date</li><li>date_time</li><li>float</li><li>integer</li><li>join</li><li>key_value_splitter</li><li>pass</li><li>phone</li><li>string</li></ul><p>You can even generate your own parsers like so:</p><pre>rails g parser MyCustomDate</pre><p>Which creates lib/decanter/parsers/my_custom_date_parser.rb:</p><pre>class MyCustomDateParser &lt; Decanter::Parsers::ValueParser<br>  parser do |value, options|    <br>    Date.strptime(value, &#39;%m/%d/%Y&#39;)<br>  end<br>end</pre><p>Now modify your decanter to reference the new parser:</p><pre>class TripDecanter &lt; Decanter::Base<br>  input :start_date, :my_custom_date<br>  input :end_date, :my_custom_date<br>  has_many :destinations<br>end</pre><h4>No Need for Strong Params Anymore</h4><p>Since we’re already defining all of the params we expect (and therefore permit) in our decanters, we can actually remove Strong Params. We do need to set the following flag on our decanters so they don’t let unwanted params through:</p><pre>class TripDecanter &lt;  Decanter::Base<br>  strict true # or use :with_exception to raise errors<br><br>  input :name<br>end</pre><p>Alas, our controller is back to old-school boilerplate Rails code:</p><pre>class TripsController &lt; ApplicationController<br>  def create<br>    @trip = Trip.decant_new(params[:trip])<br><br>    if @trip.save<br>      redirect_to trips_path<br>    else<br>      render &#39;new&#39;<br>    end<br>  end<br>end</pre><p>Not too shabby, huh?</p><p>You can find more on Decanter here: <a href="https://github.com/launchpadlab/decanter">https://github.com/launchpadlab/decanter</a></p><p>Just a heads up — the gem is &lt; 1.0 and is subject to improvement. I want to give a special thanks to <a href="https://medium.com/u/cbf6596a4827">David Corwin</a> for his hard work in making Decanter possible, and to <a href="http://launchpadlab.com/">LaunchPad Lab</a> for providing resources to the project.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=82aaa9172165" width="1" height="1" alt=""><hr><p><a href="https://medium.com/launchpad-lab/the-missing-step-in-rails-controllers-82aaa9172165">The Missing Step in Rails Controllers</a> was originally published in <a href="https://medium.com/launchpad-lab">LaunchPad Lab</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>