<?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 Matt Rice on Medium]]></title>
        <description><![CDATA[Stories by Matt Rice on Medium]]></description>
        <link>https://medium.com/@mattrice12?source=rss-e14be81a4854------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*D8vY9FXJ74XsjMg2.</url>
            <title>Stories by Matt Rice on Medium</title>
            <link>https://medium.com/@mattrice12?source=rss-e14be81a4854------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 03:16:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mattrice12/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[Uploading a PDF to s3 in Rails]]></title>
            <link>https://medium.com/lunar-collective-blog/uploading-a-pdf-to-s3-in-rails-b963a2e53feb?source=rss-e14be81a4854------2</link>
            <guid isPermaLink="false">https://medium.com/p/b963a2e53feb</guid>
            <category><![CDATA[s3]]></category>
            <category><![CDATA[heroku]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[pdf]]></category>
            <category><![CDATA[ruby]]></category>
            <dc:creator><![CDATA[Matt Rice]]></dc:creator>
            <pubDate>Mon, 21 May 2018 18:12:40 GMT</pubDate>
            <atom:updated>2018-05-23T15:53:38.742Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jZq3y5JJFBmHNfJcyfv8Zg.jpeg" /></figure><h3>Introduction</h3><p>The goal of this blog is to build a PDF, upload it to s3, and be able to download it from s3 at a later point. Without Paperclip or ActiveStorage.</p><p>The technologies used include: Rails, a PDF gem (I use Prawn), the aws-sdk gem, s3, and Heroku.</p><h3>Steps</h3><pre>A) Setup<br>  1)  Install gems in Rails<br>  2)  Setup s3 account and configuration (bucket)<br>  3)  Configure AWS environmental variables (locally and on Heroku)<br>  4)  Point to s3 bucket where PDF will be stored/retrieved<br>B) Code<br>  1)  Point to s3 bucket where PDF will be stored/retrieved<br>  2)  Build new PDF and save it locally<br>  3)  Save PDF to s3<br>  4)  View PDF at later point<br>  5)  Check if PDF exists<br>  6)  Build only if PDF doesn&#39;t exist</pre><h3>A. Setup</h3><p>Let’s setup our environment and technologies.</p><h4>1. Setup Gems</h4><p>Put the following gems in your Gemfile and bundle install. To generate a PDF, any PDF library should work. I chose Prawn since it was already in the project I jumped into. gem &#39;prawn&#39;, &#39;2.2.2&#39;</p><p>To use aws, you’ll need the aws-sdk gem. I am using version 3. gem &#39;aws-sdk&#39;, &#39;~&gt; 3&#39;</p><h4>2. Setup s3 account and configuration</h4><p>Go to <a href="https://aws.amazon.com/">https://aws.amazon.com/</a> and setup an account. Once you do that, head to your console, and under the service tab click S3. Create a bucket where you wish to store your PDFs. Since you can&#39;t change the name of the bucket after creation, name it wisely.</p><p>You will also need to find the access_key_id and secret_access_key associated with the AWS account. If you don&#39;t have these already, you can generate new ones by clicking your account name dropdown, and selecting My Security Credentials. From there click Access keys and Create New Access Key.</p><h4>3. Configure AWS environmental variables</h4><p>To access AWS through your app, you’ll need to store the access_key_id, secret_access_key, and region as Environmental Variables. The region doesn&#39;t necessarily need to be stored in an environmental variable since it is less important to keep hidden, but there are merits to being consistent.</p><p>If you’re using Heroku, you can set these variables under the Settings tab. Set new Environmental variables by assigning a name on the left and the variable on the right. E.g.:</p><pre>AWS_ACCESS_KEY_ID       &lt;your-access-key-id&gt;<br>  AWS_SECRET_ACCESS_KEY   &lt;your-secret-access-key&gt;<br>  AWS_REGION              &lt;your-region&gt;<br>  AWS_BUCKET_NAME         &lt;your-bucket-name&gt;</pre><p>If you’re using a server besides Heroku, such as the .dotenv gem, heroku local, or rails secrets, you’ll need to read their documentation on how to set environmental variables.</p><p>To work with s3 locally, assign your environmental variables and start your server at the same time: $ AWS_ACCESS_KEY_ID=&lt;your-access-key-id&gt; AWS_SECRET_ACCESS_KEY=&lt;your-secret-access-key&gt; rails s</p><h3>B. Write the Code</h3><p>Refer to the “second way” in the following aws documentation: <a href="https://docs.aws.amazon.com/AmazonS3/latest/dev/UploadObjSingleOpRuby.html">https://docs.aws.amazon.com/AmazonS3/latest/dev/UploadObjSingleOpRuby.html</a></p><h4>1. Point to s3 bucket where PDF will be stored/retrieved</h4><p>Before we build the PDF, let’s first point to s3. This method is only going to be used in this controller, so let’s make it private. This method may be better situated in the ApplicationController, but for simplicity we’ll put everything in the same Controller.</p><pre>private<br>def set_s3_object<br>  s3 = Aws::S3::Resource.new(region: ENV.fetch(&quot;AWS_REGION&quot;),<br>        access_key_id: ENV.fetch(&quot;AWS_ACCESS_KEY_ID&quot;),<br>        secret_access_key: ENV.fetch(&quot;AWS_SECRET_ACCESS_KEY&quot;))</pre><pre>  bucket_name = ENV.fetch(&quot;AWS_BUCKET_NAME&quot;)<br>  @key = &quot;hello_world.pdf&quot;<br>  @s3_obj = s3.bucket(bucket_name).object(@key)<br>end</pre><h4>2. Build new PDF and save it locally</h4><p>Using Prawn, we can build our PDF (see private method below, prawn_pdf).</p><p>Once the pdf is build, we can save the PDF to a file locally with render_file. Set your directory to be in the public folder, and make sure you gitignore that directory. No need to send it and its contents up to Github. mkdir -p will recursively create a directory and any parents that don&#39;t already exist. As an extra level of protection, we&#39;ll run this command only if the directory doesn&#39;t already exist.</p><pre>before_action :set_s3_object, only: [:build_pdf]<br>before_action :set_directory, only: [:build_pdf]</pre><pre>def build_pdf<br>  prawn_pdf.render_file(&quot;#{@directory}/#{@key}&quot;)</pre><pre>  # ...<br>end</pre><pre>private<br>def prawn_pdf<br>  Prawn::Document.new do<br>    text &quot;Hello World!&quot;<br>  end<br>end</pre><pre>def set_directory<br>  @directory = &quot;public/property/pdfs&quot;<br>  `mkdir -p #{@directory}` unless Dir.exist?(@directory)<br>end</pre><h4>3. Save PDF to s3</h4><p>Once we have the file saved locally, we can grab the file by using File.open and pass in the file location. Then we can update our s3_obj by using the method #put and passing the retrieved file.</p><pre>before_action :set_s3_object, only: [:build_pdf]<br>before_action :set_directory, only: [:build_pdf]</pre><pre>def build_pdf<br>  prawn_pdf.render_file(&quot;#{@directory}/#{@key}&quot;)</pre><pre>  File.open(&quot;#{@directory}/#{@key}&quot;, &#39;rb&#39;) do |file|<br>    @s3_obj.put(body: file)<br>  end<br>end</pre><p>If you look in your s3 bucket, you should see the file is uploaded.</p><h4>4. View PDF at later point</h4><p>Now that we have the file up on s3, let’s retrieve it and view it.</p><p>presigned_url generates a url for us towards which we can redirect. You will need to pass in the http method :get as the first argument. See documentation for other options.</p><p><a href="https://docs.aws.amazon.com/sdkforruby/api/Aws/S3/Object.html#presigned_url-instance_method">https://docs.aws.amazon.com/sdkforruby/api/Aws/S3/Object.html#presigned_url-instance_method</a></p><pre>before_action :set_s3_object, only: [:build_pdf, :view_pdf]</pre><pre>def view_pdf<br>  redirect_to @s3_obj.presigned_url(https://medium.com/:get)<br>end</pre><p>Now when a user clicks a “View PDF” link (which routers to the #view_pdf action in our controller), they will be redirected to the pdf which is hosted on s3.</p><h4>5. Check if PDF exists</h4><p>We may not want to build a new PDF if one already exists (assuming the data doesn’t change). Assume that we have a dataset which is read only for users, and only updates its data once a day. If a PDF has already been built for the present property today, we shouldn’t rebuild the PDF. We should just retrieve what already exists.</p><p>Note, if your data updates constantly, you won’t want to use a periodic check; otherwise, your users will be viewing out-of-date PDFs.</p><pre>before_action :set_s3_object, only: [:build_pdf, :view_pdf, :check_pdf]</pre><pre>def check_pdf<br>  if @s3_obj.exists? &amp;&amp; @s3_obj.last_modified.to_date == Date.current<br>    # ... return do something<br>  end<br>  # ... do something else<br>end</pre><h4>6. If PDF exists, don’t build; else, build.</h4><p>In my project, I used React to check s3 for the document on page load, and depending on whether that object exists and was created today, a link would appear to “Build PDF” or “View PDF”. If the PDF doesn’t exist and the user clicks “Build PDF”, then the build_pdf controller action gets hit, and the PDF gets built and stored in s3. If the PDF already exists and the user clicks &quot;View PDF&quot;, then the view_pdf controller action gets hit and the user is redirected to view the PDF.</p><pre>before_action :set_s3_object, only: [:build_pdf, :view_pdf, :check_pdf]</pre><pre>def check_pdf<br>  if @s3_obj.exists? &amp;&amp; @s3_obj.last_modified.to_date == Date.current<br>    return render json: { downloadable_pdf: @s3_obj.exists? }<br>  end<br>  render json: { downloadable_pdf: false }<br>end</pre><h3>Summary</h3><p>Let’s look at everything together:</p><pre>before_action :set_s3_object, only: [:build_pdf, :check_pdf, :view_pdf]<br>before_action :set_directory, only: [:build_pdf]</pre><pre>def build_pdf<br>  prawn_pdf.render_file(&quot;#{@directory}/#{@key}&quot;)</pre><pre>  File.open(&quot;#{@directory}/#{@key}&quot;, &#39;rb&#39;) do |file|<br>    @s3_obj.put(body: file)<br>  end<br>end</pre><pre>def view_pdf<br>  redirect_to @s3_obj.presigned_url(https://medium.com/:get)<br>end</pre><pre>def check_pdf<br>  if @s3_obj.exists? &amp;&amp; @s3_obj.last_modified.to_date == Date.current<br>    return render json: { downloadable_pdf: @s3_obj.exists? }<br>  end<br>  render json: { downloadable_pdf: false }<br>end</pre><pre>private</pre><pre>def set_s3_object<br>  s3 = Aws::S3::Resource.new(region: ENV.fetch(&quot;AWS_REGION&quot;),<br>        access_key_id: ENV.fetch(&quot;AWS_ACCESS_KEY_ID&quot;),<br>        secret_access_key: ENV.fetch(&quot;AWS_SECRET_ACCESS_KEY&quot;))</pre><pre>  bucket_name = ENV.fetch(&quot;AWS_BUCKET_NAME&quot;)<br>  @key = &quot;hello_world.pdf&quot;<br>  @s3_obj = s3.bucket(bucket_name).object(@key)<br>end</pre><pre>def set_directory<br>  @directory = &quot;public/property/pdfs&quot;<br>  `mkdir -p #{@directory}` unless Dir.exist?(@directory)<br>end</pre><pre>def prawn_pdf<br>  Prawn::Document.new do<br>    text &quot;Hello World!&quot;<br>  end<br>end</pre><h3>Conclusion</h3><p>I had several issues finding a complete guide to uploading and retrieving PDFs to/from s3 without Paperclip. Hopefully others in a similar struggle find this guide useful.</p><p>Note that this method does not involve attaching a file to be uploaded to s3 via a gem like Paperclip. Instead, you build a PDF on the fly, save that PDF as a file locally (or on Heroku), and then upload that file to s3. The Heroku filesystem is ephemeral, meaning that you’ll be able to store files through the method herein without worry that your Heroku server is going to get bogged down with Gigs of PDFs laying around. <a href="https://help.heroku.com/K1PPS2WM/why-are-my-file-uploads-missing-deleted">https://help.heroku.com/K1PPS2WM/why-are-my-file-uploads-missing-deleted</a> , <a href="https://devcenter.heroku.com/articles/dynos#ephemeral-filesystem">https://devcenter.heroku.com/articles/dynos#ephemeral-filesystem</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b963a2e53feb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/lunar-collective-blog/uploading-a-pdf-to-s3-in-rails-b963a2e53feb">Uploading a PDF to s3 in Rails</a> was originally published in <a href="https://medium.com/lunar-collective-blog">Lunar Collective Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Writing SQL in Rails: Speed vs. Convenience]]></title>
            <link>https://medium.com/lunar-collective-blog/writing-sql-in-rails-speed-vs-convenience-e5d8c0ec25d9?source=rss-e14be81a4854------2</link>
            <guid isPermaLink="false">https://medium.com/p/e5d8c0ec25d9</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <dc:creator><![CDATA[Matt Rice]]></dc:creator>
            <pubDate>Fri, 09 Mar 2018 15:28:43 GMT</pubDate>
            <atom:updated>2018-07-25T15:58:30.249Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8HtfsX2CFpEYxBBlNiUA9g.jpeg" /></figure><h3>Introduction</h3><p>This article discusses how to write SQL queries in Rails, and the utility of some ways over others. The deciding factors discussed here are speed versus convenience.</p><h3>Writing the Query</h3><p>Below are three different ways to write and store a SQL query in a ruby variable. I personally prefer (3) below because my text editor provides syntax highlighting making it easier to read, though any one of them do the job effectively.</p><pre>(1)<br>sql = &quot;SELECT b.title, a.name FROM books AS b JOIN authors AS a ON b.author_id = a.id;&quot;</pre><pre>(2)<br>sql = &quot;&quot;&quot;    <br>    SELECT b.title, a.name<br>    FROM books AS b<br>    JOIN authors AS a<br>    ON b.author_id = a.id;<br>  &quot;&quot;&quot;</pre><pre>(3)<br>sql = &lt;&lt;-SQL<br>    SELECT b.title, a.name<br>    FROM books AS b<br>    JOIN authors AS a<br>    ON b.author_id = a.id;<br>  SQL</pre><h3>Writing the Query in Rails</h3><p>The different ways to write SQL in Rails are divided into two main categories: Speed vs Convenience.</p><p>The first 3 described below use ActiveRecord::Base.connection and result in two classes that are ultimately stringified hashes. The benefit here is that Rails doesn’t have to do the work of instantiating a new ActiveRecord objects for each row in the results. <a href="http://blog.honeybadger.io/common-rails-idioms-that-kill-database-performance/">Instantiating ActiveRecord objects</a> <a href="https://stackoverflow.com/questions/30762575/activerecord-slow-object-instantiation">is slow</a>. Avoiding that improves performance.</p><p>But where ActiveRecord::Base.connection is more performant, Model.find_by_sql is more convenient. Here, Model.find_by_sql returns ActiveRecord objects which include functionality such as associations and dot notation, shortening and simplifying our work.</p><h4>Speed</h4><p><strong>Using ActiveRecord::Base.connection.execute()</strong></p><pre>sql = &lt;&lt;-SQL<br>    SELECT *<br>    FROM books<br>    JOIN authors<br>    ON books.author_id = authors.id;<br>  SQL</pre><pre>records_array = ActiveRecord::Base.connection.execute(sql)</pre><p>Since I’m using PostgreSQL, I get a <a href="https://deveiate.org/code/pg/PG/Result.html">PG::Result object</a>. If I was using MySQL, I would get a<a href="http://www.rubydoc.info/gems/mysql/2.8.1/Mysql/Result">Mysql::Result object </a>. Note the difference; PG::Result gives different methods than Mysql::Result. Here, I will only discuss the former.</p><p>PG::Result includes a set of methods you can use on the dataset. In addition, the PG::Result object is an array of stringified hashes; therefore, the normal Ruby and Rails methods for arrays and hashes work on this dataset as well.</p><p>Use records_array.values to see the values.</p><p>A caveat to using execute is <a href="https://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/DatabaseStatements.html#method-i-execute">depending on your database connector, the result returned by this method might require manual garbage collection</a>. Consider using exec_query instead.</p><p><strong>Using ActiveRecord::Base.connection.exec_query()</strong></p><pre>records_array = ActiveRecord::Base.connection.exec_query(sql)</pre><p>This produces a <a href="http://api.rubyonrails.org/classes/ActiveRecord/Result.html">ActiveRecord::Result object</a>. Despite being a class in the ActiveRecord module, ActiveRecord::Result does not offer the ActiveRecord conveniences of associations and dot notation. ActiveRecord::Result is more like PG::Result; and though it has fewer methods than PG::Result, they are arguably more useful for viewing the resulting data in rails console. Indeed, people tend to favor .exec_query because calling .columns, .rows, and .to_hash on the results improve their readability.</p><p>Like PG::Result, ActiveRecord::Result is an array of stringified hashes, so the Ruby and Rails methods apply here as well.</p><p><strong>Using ActiveRecord::Base.connection.select_all</strong></p><pre>ActiveRecord::Base.connection.select_all(sql)</pre><p>This produces an ActiveRecord::Result instance like with .exec_query, and so the results are utilized in the same way.</p><h4>Convenience</h4><p><strong>Using Model.find_by_sql</strong></p><pre>Book.find_by_sql(sql)</pre><p>Unlike with ActiveRecord::Base, calling .find_by_sql on a one of your active record models provides an ActiveRecord object rather than a stringified hash. As mentioned above, this gives you all the conveniences of ActiveRecord at the expense of performance. But unless you are grabbing thousands of records, the performance loss is unnoticeable.</p><p>Another downside of find_by_sql that is not present in the ActiveRecord::Base methods is that if you are joining other tables and trying to view the results in rails console, the return value doesn’t show any columns from joined tables. However, those columns are still part of the results and can be accessed, as demonstrated below.</p><pre>books = &lt;&lt;-SQL<br>    SELECT books.id, books.title, authors.name<br>    FROM books<br>    JOIN authors<br>    ON books.author_id = authors.id;<br>  SQL</pre><pre>=&gt; [#&lt;Book:0x007f32241v810 id: 1, title: “Lord of the Rings”&gt;,<br>    #&lt;Book:0x007f32241v930 id: 2, title: “The Dark Tower”&gt;,<br>    #&lt;…]</pre><pre>books.first.name<br>=&gt; “J. R. R. Tolkien”</pre><h4>Conclusion</h4><p>In sum, a large deciding factor on how to write SQL queries within Rails depends on whether you’re looking for a fast query or for simpler code. If you’re processing only a small amount of data, then Model.find_by_sql will get you everything you need. If you’re processing a lot of data that is or will result in noticeably long page-loads, then go with ActiveRecord::Base.connection.</p><h4>Further Reading</h4><ul><li><strong><em>ActiveRecord::Base</em></strong>, <a href="http://api.rubyonrails.org/classes/ActiveRecord/Base.html">http://api.rubyonrails.org/classes/ActiveRecord/Base.html</a></li><li><strong><em>PG::Result</em></strong>, <a href="https://deveiate.org/code/pg/PG/Result.html">https://deveiate.org/code/pg/PG/Result.html</a></li><li><strong><em>ActiveRecord::Result</em></strong>, <a href="http://www.rubydoc.info/docs/rails/3.2.8/ActiveRecord/Result">http://www.rubydoc.info/docs/rails/3.2.8/ActiveRecord/Result</a></li><li><strong><em>find_by_sql</em></strong>, <a href="https://apidock.com/rails/ActiveRecord/Querying/find_by_sql">https://apidock.com/rails/ActiveRecord/Querying/find_by_sql</a></li><li><strong><em>Speed vs. Convenience</em></strong>, <a href="http://patshaughnessy.net/2010/9/4/activerecord-with-large-result-sets---part-1-select_all-vs--find">http://patshaughnessy.net/2010/9/4/activerecord-with-large-result-sets---part-1-select_all-vs--find</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e5d8c0ec25d9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/lunar-collective-blog/writing-sql-in-rails-speed-vs-convenience-e5d8c0ec25d9">Writing SQL in Rails: Speed vs. Convenience</a> was originally published in <a href="https://medium.com/lunar-collective-blog">Lunar Collective Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Life at Lunar Collective]]></title>
            <link>https://medium.com/lunar-collective-blog/life-at-lunar-collective-12872a59ea08?source=rss-e14be81a4854------2</link>
            <guid isPermaLink="false">https://medium.com/p/12872a59ea08</guid>
            <category><![CDATA[junior-developer]]></category>
            <category><![CDATA[growth]]></category>
            <category><![CDATA[consultancy]]></category>
            <category><![CDATA[consultant]]></category>
            <category><![CDATA[developer]]></category>
            <dc:creator><![CDATA[Matt Rice]]></dc:creator>
            <pubDate>Wed, 06 Dec 2017 20:14:03 GMT</pubDate>
            <atom:updated>2017-12-06T20:14:03.188Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi. I am a developer at Lunar Collective, a Web Consulting company in Austin, Texas founded by Justin Herrick. I have been with Lunar Collective for 10 months now and frankly love my job. In short, I have the autonomy to work on a diverse and engaging set of projects with a boss and mentor who trusts my opinions and decisions and contributes positively to my love of coding and growth as a young developer. Okay that was long. Let me break down what I’m talking about:</p><h4>“I have the autonomy…”</h4><p>As a Web Consultancy, we take contracts to work on projects that need upgrading, fixing, or augmenting. Each project I jump on, I take the leading role in approaching and working on the stories that we create together with the client. That being said, if I am struggling with a problem or concept, Justin acts as fallback support to pair with me or discuss, understand, and overcome the problem.</p><h4>“…to work on a diverse and engaging set of projects…”</h4><p>In the last ten months I have worked on seven separate projects. Two of these projects are internal and continuously worked on. The other four are for clients. Of these contracts, I have worked extensively in Ruby on Rails, React / Redux, jQuery, Ember, Elixir, and Phoenix.</p><p>I started out working on one project at a time. However, within the last few months I started balancing two projects simultaneously. This constantly changing environment is ideal for me as it prevents burnout and is very growth-focused.</p><p>In addition to working on applications, Lunar Collective encourages blogging. So far I have written and published six blog posts through Lunar Collective (soon to be eight including this one and another one that I accidentally wrote while writing this one). Having the freedom to research and write about a topic allows me to investigate that concept in ways I wouldn’t be able to while coding. More importantly, if I want to research and write about these concepts, I don’t have to do it in my own time.</p><h4>“…with a boss and mentor who trusts my opinions and decisions…”</h4><p>Justin displays a very growth-focused perspective towards his employees. And he knows that there is more than one way to climb a mountain. By allowing me to find my path up the mountain, he has allowed me to encounter problems and discover solutions. He offers help and guidance if I have trouble starting or run into anything that I find insurmountable, but generally it is my own discovery. Afterwards, he pairs with me to refine that path I chose, so the next time I approach a similar mountain, I come to it with more experience.</p><h4>“…and contributes positively to my love of coding and growth as a young developer…”</h4><p>This is true for all of the above reasons, and for the reason that he somehow tricks me into achieving things outside of my comfort zone — namely, client interaction — but in a way that is not anxiety inducing. I can now confidently say that I have client-facing experience, all of which was positive. Additionally, I now have a lot of experience training clients and other developers in languages and frameworks in which they weren’t familiar.</p><p>Justin also recognizes the importance of being involved around Austin and in the Tech scene. He has frequently encouraged me to give talks about my experiences and research. That egg may take a little longer to hatch, but the fact that he encourages such opportunities is something that I value in an employer.</p><h4>Conclusion</h4><p>There is much more to be said about Lunar Collective, about Justin, and about myself; but this definitely covers the highlights that I could summarize in one 39 word sentence. I will conclude by saying that I took this job with a growth-oriented mindset, and in that respect I don’t think I could have found a better opportunity.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=12872a59ea08" width="1" height="1" alt=""><hr><p><a href="https://medium.com/lunar-collective-blog/life-at-lunar-collective-12872a59ea08">Life at Lunar Collective</a> was originally published in <a href="https://medium.com/lunar-collective-blog">Lunar Collective Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ruby Access Control: Private Methods]]></title>
            <link>https://medium.com/lunar-collective-blog/ruby-access-control-three-formats-6ac868d46af5?source=rss-e14be81a4854------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ac868d46af5</guid>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[access-control]]></category>
            <category><![CDATA[inheritance]]></category>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[ruby]]></category>
            <dc:creator><![CDATA[Matt Rice]]></dc:creator>
            <pubDate>Wed, 29 Nov 2017 16:03:06 GMT</pubDate>
            <atom:updated>2017-11-29T18:55:05.463Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XQ-Jm8pc0HAsF_hJw0eFhA.jpeg" /></figure><p>Access control defines how accessible methods are throughout the application. This is important to signal your intent to other developers and prevent a method from being used outside of its intended purpose. Using Object Oriented terminology, this is Encapsulation.</p><p>The three levels of access control are public, protected, and private. This blog post primarily covers the private level, though the syntax detailed below applies similarly to public and protected.</p><p>Marking a method as private prevents the method from being called outside of the class in which it is defined. Contrast this with public methods can be called on an instance of a class anywhere in the application. Private methods are not visible or accessible from outside the class, and calling them from outside the class will result in a NoMethodError. However, other methods within the class can call private methods. They can be thought of as class helper methods.</p><p>Marking a method as private (or public or protected) is as follows:</p><pre><strong># Block Format</strong></pre><pre>class Example<br>  def method_public<br>  end</pre><pre>  private<br>  def method_a<br>  end</pre><pre>  def method_b<br>  end<br>end<br></pre><pre><strong># Prepending Format</strong></pre><pre>class Example<br>  def method_public<br>  end</pre><pre>  private def method_a<br>  end</pre><pre>  private def method_b<br>  end<br>end<br></pre><pre><strong># List Format</strong></pre><pre>class Example<br>  def method_public<br>  end</pre><pre>  def method_a<br>  end</pre><pre>  def method_b<br>  end</pre><pre>  private :method_a, :method_b<br>end</pre><h4>Block Format</h4><p>Using Block Format, methods defined below the access level keyword (public, protected, or private) assigns those methods to that access level. The block format serves as a good visual cue, dividing the class into distinct sections. This convention is quickly recognized by the larger Ruby community and serves little ambiguity.</p><pre>class User<br>  def name<br>    “#{first_name} #{last_name}”<br>  end</pre><pre>  private<br>  def first_name<br>    “John”<br>  end</pre><pre>  def last_name<br>    “Smith”<br>  end<br>end</pre><pre>user = User.new<br>user.name<br>#=&gt; John Smith</pre><pre>user.first_name<br>#=&gt; `&lt;main&gt;’: private method `first_name’ called for #&lt;User:0x007f8b988b29c0&gt; (NoMethodError)</pre><h4>Prepending Format</h4><p>This way gives an immediate signal that a method is private. This allows the<br>developer to write private methods anywhere within the class and so spends less time worrying about organization. The downside is that worrying less about organization may result in much more cluttered code.</p><pre>class User<br>  def name<br>    “#{first_name} #{last_name}”<br>  end</pre><pre>  private def first_name<br>    “John”<br>  end</pre><pre>  private def last_name<br>    “Smith”<br>  end<br>end</pre><h4>List Format</h4><p>Another and less used way to write private methods is to initially write all<br>methods as if they were public, then at the bottom use the private keyword and list the methods which should be private. You can do this with public and protected keyword too.</p><pre>class User<br>  def name<br>    “#{first_name} #{last_name}”<br>  end</pre><pre>  def first_name<br>    “John”<br>  end</pre><pre>  def last_name<br>    “Smith”<br>  end</pre><pre>  private :first_name, :last_name<br>end</pre><p>The benefit of this syntax is that the you can quickly see all the methods<br>listed that are public, protected, and private. The downside of this syntax is<br>that it is less organized and creates much more ambiguity at first look,<br>especially in larger classes. All methods are clumped together, often in no<br>specific order, and then only on 3 or so lines is the developer made aware of<br>which methods are public, private, or protected. Anytime the developer needs to know what level of access the method has, they must scroll back to those 3 lines to verify.</p><p>That being said, this syntax should be used in certain situations — namely, with inheritance. Subclasses inherit methods and the level of access each method has.</p><p>The problem occurs when we want to change the access level of an inherited<br>method. Using the block or prepending option requires us to redefine the method itself with the different access level. These approaches are not DRY and require the developer to make identical changes in multiple places which opens up the possibility for mistakes. The cleaner and safer approach is to use the List Format:</p><pre>class Bot &lt; User<br>  def operation_name<br>    name + “, Serial: “ + serial_number<br>  end</pre><pre>  def serial_number<br>    rand(10000…99999).to_s<br>  end</pre><pre>  private :name, :serial_number<br>end</pre><pre>bot = Bot.new<br>puts bot.operation_name<br>#=&gt; John Smith, Serial: 39820</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ac868d46af5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/lunar-collective-blog/ruby-access-control-three-formats-6ac868d46af5">Ruby Access Control: Private Methods</a> was originally published in <a href="https://medium.com/lunar-collective-blog">Lunar Collective Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ember View Deprecations: classNames and classNameBindings]]></title>
            <link>https://medium.com/lunar-collective-blog/ember-view-deprecations-classnames-and-classnamebindings-adf36a2f3ea5?source=rss-e14be81a4854------2</link>
            <guid isPermaLink="false">https://medium.com/p/adf36a2f3ea5</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[emberjs]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[ember]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Matt Rice]]></dc:creator>
            <pubDate>Thu, 02 Nov 2017 15:08:40 GMT</pubDate>
            <atom:updated>2017-11-02T15:19:40.636Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VXWAtBSC_rjhWUmcJx2jdg.jpeg" /></figure><h4>Issue</h4><p>I recently started a working on a contract to fix bugs that appeared after a company updated their app from Ember 1.13 to Ember 2.14. One issue that affected several areas of the app was the deprecation of classNames and classNameBindings in the View file.</p><p><a href="https://www.emberjs.com/deprecations/v1.x/#toc_ember-view">As of 2.0, Views are deprecated</a>. Now the classNames and classNameBindings functionality goes into Components. In my situation, this created a problem since classNames and classNameBindings were being used to add classes to the Application container element rather than some deeper Component.</p><h4>Functionality</h4><p>In trying to solve this issue, I referenced the following:</p><ul><li>Issue: <a href="https://github.com/emberjs/ember.js/issues/11486">https://github.com/emberjs/ember.js/issues/11486</a></li><li>Related Ember Docs: <a href="https://www.emberjs.com/api/ember/2.14/classes/Ember.Component/properties">https://www.emberjs.com/api/ember/2.14/classes/Ember.Component/properties</a></li></ul><p>The intended effect of classNames is to set the container element’s class to the strings in the classNames array. For example:</p><pre>export default Ember.Component.extend({<br>  classNames: [‘app-container’]<br>});</pre><pre>## adds the class app-container to the container element:<br>&lt;div id=”ember1&quot; class=”ember-view app-container”&gt;</pre><p>The intended effect of classNameBindings is similar. classNameBindings is set to an array of properties (rather than strings). The return values of these properties defined in the Component are added to the container element’s class (see Example A). If the property returns a boolean value, the property name itself will be added to the class name if the boolean value is true (see Example B).</p><p><strong>Example A:</strong></p><pre>export default Ember.Component.extend({<br>  classNameBindings: [‘isLoggedIn’],<br>  isLoggedIn: ‘show-user’<br>});</pre><pre>## adds the class show-user to the container element:<br>&lt;div id=”ember1&quot; class=”ember-view show-user”&gt;</pre><p><strong>Example B:</strong></p><pre>export default Ember.Component.extend({<br>  classNameBindings: [‘isLoggedIn’],<br>  isLoggedIn: true<br>});</pre><pre>## adds the class is-logged-in to the container element:<br>&lt;div id=”ember1&quot; class=”ember-view is-logged-in”&gt;</pre><h4>Solution</h4><p>The Ember app that I am working in had both Components and Views. However, since Views became deprecated, I needed another way to add the desired classes to the application container. This is what it looked like using Ember 1.13 Views:</p><pre>application/view.js</pre><pre>export default Ember.View.extend({<br>  classNames: [‘app-container’],<br>  classNameBindings: [‘navBarFixed’, ‘shoppingListIsOpen’],<br>});</pre><p>Using classNameBindings, navBarFixed and shoppingListIsOpen would be converted into hyphenated classes and added to the container element when the associated properties returned true. Let’s focus on navBarFixed for now:</p><pre>application/controller.js</pre><pre>export default Ember.Controller.extend({<br>  navBarFixed: function() {<br>    return this.get(‘scrollTop’) &gt; toolbarDistanceFromTop;<br>  }.observes(‘scrollTop’)<br>});</pre><p>Transitioning to v2.0, this same result needs to happen in a different way. My fix was to create another function that runs whenever the user scrolls, and manually adds the class nav-bar-fixed when this.navBarFixed() returned true:</p><pre>application/controller.js</pre><pre>export default Ember.Controller.extend({<br>  setNavBar: function() {<br>    let $container = $(‘.ember-application &gt; .ember-view’);<br>    if (this.navBarFixed()) {<br>      $container.addClass(‘nav-bar-fixed’);<br>    } else {<br>      $container.removeClass(‘nav-bar-fixed’);<br>    }<br>  }.observes(‘scrollTop’)<br>});</pre><p>Each template and <a href="https://guides.emberjs.com/v2.13.0/components/customizing-a-components-element/">component</a> creates a new element with .ember-view. I used this to grab the first .ember-view inside the application (which is the application template) by using the child selector, &gt;. Otherwise, I might get some unintended consequences.</p><p>Fortunately fixing the Shopping List proceeded in almost the exact same way as fixing the Nav Bar. Since this was a click event rather than a scroll event, I added it as an action and could use toggleClass() rather than addClass().</p><pre>application/controller.js</pre><pre>export default Ember.Controller.extend({<br>  action: {<br>    toggleOpenMenu: function() {<br>      let $container = $(‘.ember-application &gt; .ember-view’);<br>      $container.toggleClass(‘shopping-list-column-is-open’);<br>    }<br>  }<br>});</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=adf36a2f3ea5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/lunar-collective-blog/ember-view-deprecations-classnames-and-classnamebindings-adf36a2f3ea5">Ember View Deprecations: classNames and classNameBindings</a> was originally published in <a href="https://medium.com/lunar-collective-blog">Lunar Collective Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Three I’s of Meaningful Names: Information, Identity, and Institution]]></title>
            <link>https://medium.com/lunar-collective-blog/the-three-is-of-meaningful-names-information-identity-and-institution-d05b0711ea36?source=rss-e14be81a4854------2</link>
            <guid isPermaLink="false">https://medium.com/p/d05b0711ea36</guid>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[variables]]></category>
            <dc:creator><![CDATA[Matt Rice]]></dc:creator>
            <pubDate>Fri, 29 Sep 2017 14:45:21 GMT</pubDate>
            <atom:updated>2017-09-29T15:00:44.591Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gk0rjSfLu1gavZYpUzE2sg.jpeg" /></figure><p>Creating meaningful names for variables, functions, and classes will not make your program run faster. The benefits are strictly for other developers and your future self to better and more quickly understand code you wrote. This facilitates code review and later contributions.</p><p>Ideally, our goal is to write code that reads like a book rather than a math or logic puzzle. Part of that involves writing well-crafted names that convey meaning quickly and effectively. Fortunately, there several rules and guidelines to give direction; unfortunately, there are a lot of rules to remember. This write-up is an effort to <a href="https://en.wikipedia.org/wiki/Chunking_(psychology)">chunk</a> this information into three larger rule categories, thereby making the several smaller rules easier to remember. Thus, meaningful names should be informative, identifiable, and institutional.</p><p>One last thing before I being: This blog was influenced and inspired by Robert C. Martin’s book, <a href="https://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882/ref=sr_1_1?ie=UTF8&amp;qid=1506620548&amp;sr=8-1&amp;keywords=clean+code"><em>Clean Code: A Handbook of Agile Software Craftsmanship</em></a>. It should be required reading for any developer.</p><h3>Information</h3><p>First and foremost, our names should convey <em>Information</em>. Code is not impressionistic; it has a specific meaning that we want to make as clear as possible.</p><p>If code is to read like a book, then names should be meaningful enough to convey information. The sentence A man went to the place for something conveys nothing substantive. a went to b for c conveys even less. Contrast this with The King of France went to the gallows to die. This conveys meaning, paints a picture in our mind, and is memorable. Names in code should do the same.</p><h4>Informative Names Reveal Intent</h4><p>Variable, function, and class names should reveal the reason for why they exist, what they do, and how they are used. Codebases are puzzling enough; therefore, we should aim to make their individual pieces as apparent as possible.</p><p>Single letter names such as a convey no information as to the author’s intent or it’s purpose in the code. These names can refer to virtually anything and offer no insight to its own meaning or the surrounding context. With a few exceptions, single letter names are inappropriate even in the narrowest scope.</p><p>Names such as user give a better indication of what the variable references, but intent is still blurry in all but a few limited situations.</p><p>In both situations, we might infer intent by the surrounding context. But context is a two way street. Context is created by a collection of well defined pieces. The more vague the pieces, the more vague the context.</p><p>Names such as clientRecord or topEmployee give more insight on their purpose. These names do a better job at conveying intent while also giving sufficient enough detail to contribute positively to the entire context.</p><h4>Informative Names Avoid Disinformation</h4><p>Just as names should reveal intent and contribute to context, they should not also muddy the intent or context. For example, The King of France went to the gallows to sort of die. The phrase <em>sort of</em> detracts quite a bit from this sentence. It makes us question our initial assumption that he would be hanged and doesn’t replace it with anything useful. Similarly, disinformation in code comes in the form of contradicting the normal assumptions we make.</p><p>Do not vary from a word’s common or entrenched meaning. For example, don’t use address to refer to a user’s e-mail address.</p><p>Do not use names that confuse data-types. E.g., let bestDoctorArray = “Matt Smith”. Any variable with array in the name should be an array.</p><p>Do not break capitalization convention. Capitalization says a lot about meaning. Subject to your language’s or codebase’s convention: Variables are usually camelCase or snake_case with the first letter lowercase, constants are CAPITALIZED, and classes are CamelCase with the first letter of each word capitalized. Deviating from this will leave future developers confused as to (1) the purpose of the object, (2) why this was written a certain way while others were written differently, and (3) which way they should write the name.</p><h4>Informative Names Avoid Noise</h4><p>Like disinformation, noise impacts overall meaning; however, unlike disinformation, it does so less directly. Instead, noise is the presence of extra, meaningless information that distinguishes names for the compiler rather than for the developer. In extreme cases, too much noise in your code base is like trying to have a conversation in a club — you might understand a few words out of an entire sentence, but you’ll struggle to grasp the overall meaning.</p><p>The most common ways noise is created is by making small spelling changes to a name (e.g., user, uzer, userr) and adding numbers to letters or variables to show that they are similar but still different (e.g., a1, a2, a3). While these names are distinguishable enough for the compiler, their differences do not convey anything useful to the developer.</p><p>Take the title of this article, for example. If I named it The 3 I’s of Meaningful Names: i1, i2, and i3, I’ve conveyed nothing meaningful that hasn’t already been said; furthermore, I’ve conveyed no useful distinction between them (Credits to Matthew Giardina for thinking up this beautiful title that I so nearly used).</p><p>Noise also occurs in the form of redundancy when none is needed. For example: let Car = {carMake: …, carColor: …};</p><p>Should be: let Car = {make: …, color: …};</p><p>Additionally, affixing Info or Data to the end of names adds no additional information that their base word doesn’t have. userInfo and user convey the same meaning; similarly with productData and product.</p><h3>Identity</h3><p>The second I for creating meaningful names is that they should be <em>Identifiable</em>. Being identifiable is broadly defined as being able to be both immediately understood and searchable by the developer.</p><h4>Pronounceable</h4><p>A developer can better identify and immediately understand a name that is pronounceable and spelled correctly. Most of us are decent enough at reading — especially those who read blogs — that we can process pronounceable words more quickly than words full of noise or abbreviations. Many people, myself included, pronounce what we read. Therefore reading getCoAddr(c) { return c.addr }; takes me a bit more time to parse than getCompanyAddress(company) { return company.address };.</p><h4>Distinguishable</h4><p>Avoid names that look too similar. Subtle differences are too hard to distinguish at a quick glance. For example, getAccountsForAllCurrentEmployees() and getAccountsForAllFormerEmployees(). Depending where our eyes fall on the word, we may not see the the distinction, especially when parsing hundreds of lines of code.</p><p>When reading, we frequently look at the the overall structure rather than the the details of the the word. Consider the the older meme: &quot;Aoccdrnig to a rscheearch at Cmabrigde Uinervtisy, it deosn’t mttaer in waht oredr the ltteers in a wrod are, the olny iprmoetnt tihng is taht the frist and lsat ltteer be at the rghit pclae&quot;. While misspellings are frequent and distinguishable here, we can still read and understand meaning. This adds credence to the the point that we overlook details. As further support to my point that we gloss over details, you may have overlooked the the fact that every time I used the the word “the” in this section (outside of the the quotes), I used it twice.</p><p>In conclusion, make sure differences are sufficiently distinct.</p><h4>Searchable</h4><p>Not only are pronounceable names easier to read, but they add that extra distinction to be more easily searchable. Let’s build the above function out a little more:</p><pre> const getCoAddr = (c) =&gt; {<br>   switch (c.state) {<br>     case “TX”:<br>       console.log(c.addr);<br>       break;<br>     case “CA”:<br>       console.log(“Out of State”);<br>       break;<br>   };<br> };</pre><p>If I tried to use any text-editor’s find command for argument c, I’d have excess results returned to me. This becomes even more problematic as the project grows and I’m searching between files for names. This problem isn’t limited to single letter names. It also extends to names that aren’t sufficiently meaningful, such as user. If the name user is used at all, it will most likely be used throughout the project. Searching the project for all instances of user will be overwhelming to the point where the search feature won’t be useful. Note that the default search for many text-editors will return all instances of user even if it is part of a larger word such as current_user or new User or aMuseRecording.</p><h3>Institution</h3><p>The <em>Institution</em> category gets a little more spiritual. It is our third I and has perception beyond the other two. It points us to look both within and without our project and write names that are in harmony with the conventions set forth.</p><p>Setting spirituality aside, meaningful names should be institutional and follow the conventions (1) set internally by the codebase in which you are writing and (2) set externally by the programming language itself. Keeping with these conventions adds meaning that future developer will understand. Deviating from convention adds noise and false clues in the codebase.</p><h4>Internal Institution</h4><p>This type of convention will typically differ between codebases written by different people. The differences may not be very substantial. However, deviating from the consensus will detract from meaning.</p><p>I mentioned one stylistic convention above, and that is with how names are capitalized. If the consensus for constants is that they are written in all caps, then continue doing so for constants. If all file names are snake_case while the files’ titular function names are camelCase, stick with that convention. There is usually a meaningful reason for it. Even if there isn’t a meaningful reason for it, there is a pattern. And breaking the pattern creates noise and disorganization — especially when files are organized alphabetically.</p><p>Another internal convention is deciding on which verb to prepend to function names (e.g., get, retrieve, and fetch); or noun to append to variable names (e.g., nameArray, nameGroup, or simply names). It doesn’t matter which verb or noun you choose, just make sure it is used consistently in the code base.</p><p>Assume I have two functions each making similar GET requests but one is named getAccounts while the other is called retrieveRecords. Implicitly it seems that there is some difference between these functions other than the data being requested. If there is no difference, then they should both have the same prefix. If there is a difference, then the names should better telegraph that difference.</p><h4>External Institution</h4><p>External institution involves the conventions of the language in which your project is written. This takes second priority over maintaining internal institution. However, if the internal convention deviates substantially from the language’s overall stylistic and naming convention, this may warrant a discussion on how to revert or better conform to the language’s conventions.</p><p>Not only are the language’s conventions more tried and true; any person first coming into a codebase that doesn’t follow the external conventions will take longer to ramp up to speed. This is not as true if the codebase follows the language’s stylistic and naming conventions.</p><p>The best place to learn of a language’s convention is to refer to their style guide. However, here are a few universal standards:</p><ul><li>Classes should be capital CamelCase nouns or noun-phrases — e.g., Users or UserAccounts.</li><li>Variables should be lower camelCase or snake_case nouns or noun-phrases — e.g., selectedUser or selected_user.</li><li>Function and Methods should be lower camelCase or snake_case, and begin with a verb and end with a noun or noun-phrase — e.g., getUsers or get_accounts.</li></ul><h3>The Scope Qualifier</h3><p>The above rules <em>can</em> (but arguably <em>shouldn’t</em>) be bent in a few small circumstances based primarily on the level of scope. I think of it as the <em>Inverse Rule of Scope</em>: The broader the scope, the more strictly the rules should be followed; the narrower the scope, the more loosely. Most of the above principles should be adhered to regardless of scope, but there is a little wiggle room for the length and detail of the names. Note: This rule is not another <em>I</em> for creating meaningful names; it is just a qualifier.</p><h4>Single letter names</h4><p>Because single letter names do not convey the intent of the author, they should be avoided. However, when their use is part of a language’s larger convention, then that convention conveys intent. For example, JavaScript uses e as shorthand for an event. Many languages use i to signify a counter in a for loop or the index in an iterative operation. This meaning becomes lost the further you move from where the variable is declared. As a result, these should only be used in narrow scope.</p><h4>Vaguely named variables</h4><p>These are typically acceptable in short functions and narrow scope where the context is completely obvious. However, it made still be worthwhile to write a meaningful name. What is obvious to one person may be puzzling to the next.</p><h4>Searchable names</h4><p>If the scope of what you are searching is narrow, likely any word won’t be too hard to find. However single letter names will still create problems. Additionally, if the same name is used many times throughout the file, you may experience some mild frustration trying to jump to the variable within any one particular section.</p><h3>The Abstraction Qualifier</h3><p>Given our desire to keep our code DRY, using more generic names in abstractions is permissible. However even in a highly abstract function, there are still much better names than obj or a1, a2, a3.</p><h3>Conclusion</h3><p>Hopefully these categories are broad enough to include most rules for creating meaningful names (even ones I failed to mention), yet specific enough so that the details can be remembered. Do make an effort to creating meaningful names. They help everyone working in the codebase. In turn, it might encourage others to write meaningful names, as well.</p><h3>Sources</h3><ol><li>Robert C. Martin, <em>Clean Code: A Handbook of Agile Software Craftsmanship</em></li><li><em>clean-code-javascript</em>, <a href="https://github.com/ryanmcdermott/clean-code-javascript">https://github.com/ryanmcdermott/clean-code-javascript</a></li><li><em>ruby-style-guide</em>, <a href="https://github.com/bbatsov/ruby-style-guide">https://github.com/bbatsov/ruby-style-guide</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d05b0711ea36" width="1" height="1" alt=""><hr><p><a href="https://medium.com/lunar-collective-blog/the-three-is-of-meaningful-names-information-identity-and-institution-d05b0711ea36">The Three I’s of Meaningful Names: Information, Identity, and Institution</a> was originally published in <a href="https://medium.com/lunar-collective-blog">Lunar Collective Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A SOLID Solution: Part III]]></title>
            <link>https://medium.com/lunar-collective-blog/a-solid-solution-iii-9a2f8439633c?source=rss-e14be81a4854------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a2f8439633c</guid>
            <category><![CDATA[css]]></category>
            <category><![CDATA[web-design]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[software-craftsmanship]]></category>
            <category><![CDATA[scss]]></category>
            <dc:creator><![CDATA[Matt Rice]]></dc:creator>
            <pubDate>Mon, 22 May 2017 14:07:29 GMT</pubDate>
            <atom:updated>2017-05-26T17:07:44.550Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eXkaJc9sgFM-IC31T8_HTw.jpeg" /></figure><h3>Introduction</h3><p>Find Part I <a href="https://blog.lunarcollective.co/a-solid-solution-to-css-9f48f5663332">here</a> and Part II <a href="https://medium.com/@mattrice12/a-solid-solution-ii-f30507a8b134">here</a>.</p><p>Continuing our discussion, this section covers the three SOLID principles that I believe are focused more on creating new classes rather than a more general discussion of CSS structure. I begin with the Open/Close Principle which states that entities should be open for extension but closed for modification. As will be discussed further, once several areas of your site depend on a CSS class, changes to that class should be indirect through extension rather than direct amendment.</p><p>Then I discuss the Interface Segregation Principle which states that client specific interfaces are better than one general purpose interface. This adds to the Open/Close Principle in reassuring that it is ‘okay’ to add multiple CSS classes to an element rather than reducing all the CSS down into one class. This keeps the base class very general and re-usable. By having general base classes, you will create new classes to write new properties rather than unwrite unnecessary properties.</p><p>I close with the Dependency Inversion Principle which states that abstractions should not depend on details; details should depend on abstractions. This reinforces the points of the above principles: By keeping the base classes very general, new classes can add useful properties rather than remove unnecessary properties.</p><h3>Lesson 2: Extending Classes Responsibly</h3><h4>Open/Close Principle</h4><p>The Open/Close Principle (OCP) is the idea that base abstractions should be open for extension but closed for modification. Modifying base abstractions is generally a bad idea and should be done very rarely if at all. Doing so is likely to cause conflicts in the details that depend on them.</p><p>In my case, the base abstractions were my grid classes. Thus, I violated OCP by modifying the grid directly when combining .container with .services. Rather, I should have stuck with my initial approach of extending the grid by adding additional, specific classes. Conflicts arose by modifying the grid because everything in the site was built on top of the grid. Moreover, in specific instances the grid reflected changes in different, unpredictable ways, depending on what other classes extended the grid in that instance. Many of the conflicts that arose were not immediately obvious and took longer and more work to rectify. I ended up adding more classes than I reduced to temporarily fix the problem, making the HTML and CSS unnecessarily bloated.</p><p>Rather than modifying the grid directly, create additional, specific classes that you can use wherever the change is needed:</p><pre>.container {<br>  display: flex;<br>  justify-content: center;<br>}</pre><pre>.container {<br>  &amp;.services {<br>    justify-content: space-between;<br>  }<br>}</pre><h4>Interface Segregation Principle</h4><p>Interface Segregation Principle (ISP) means many client specific interfaces are better than one general purpose interface. In other words, no element should be forced to implement an interface it doesn’t use.</p><p>By combining .services with .container, I made .container into a much more general purpose block. As a result, many applications of .container didn’t need the baggage that now came with .container, and I had to create additional, specific classes to remove that baggage.</p><p>My opinion on this is that doing so to a small extent is not egregious. The following example is okay even though I may later add a specific class to a container that sets justify-content: space-between;. It becomes a problem when excessively adding properties, especially non-structure properties to the abstraction. You may notice it is a problem further down the road when you end up creating a class for almost every container that changes the properties you set in your abstraction. However, by the time you notice the problem, it may be too late and very dangerous to fix. Therefore, I think setting up a minimal grid is okay, even if you have to append an additional class to overwrite some properties later.</p><pre>// okay<br>.container {<br>  display: flex;<br>  flex-wrap: nowrap;<br>  justify-content: center;<br>  align-items: center;<br>  width: 100vw;<br>}</pre><pre>// bad<br>.container {<br>  display: flex;<br>  flex-wrap: nowrap;<br>  justify-content: center;<br>  align-items: center;<br>  width: 100vw;<br>  font-size: .95em;<br>  padding-top: 40px;<br>  margin-top: 40px;<br>}</pre><h4>Dependency Inversion Principle</h4><p>Finally, The Dependency Inversion Principle (DIP) also plays an important role. This principle states that abstractions should not depend upon details; details should depend upon abstractions. Contrarily, by adding bandages to treat a broken grid-system (my abstractions), the functionality of my grid depended on more specific, detail-like classes.</p><p>In the above ‘bad’ example, assume I created this with the page body in mind. However, I also want to use .container to create my header and footer. Because I have margin-top: 40px; my header and footer is going to have a white gap on the top — which in my case is undesirable. Because I’m trying to play it safe and not modify the grid, I’m going to create a specific class to remove this margin. And I’ll add it to any container that doesn’t need the margin.</p><p>Now, because I didn’t follow the Interface Segregation Principle, I have to create specific classes to fix my abstraction, thus breaking the Dependency Inversion Principle. I should instead create a minimalist, general class and create specific classes to add what I need, where I need it.</p><pre>.container {<br>  display: flex;<br>  flex-wrap: nowrap;<br>  justify-content: center;<br>  align-items: center;<br>  width: 100vw;</pre><pre>  &amp;.header-block {<br>    font-size: 1.5em;<br>    padding-top: 5em;<br>    background: #222;<br>    border-bottom: 10px solid #000;<br>    color: white;<br>  }</pre><pre>  &amp;.body-block {<br>    font-size: .95em;<br>    margin-top: 40px;<br>    padding-top: 5em;<br>  }</pre><pre>  &amp;.footer-block {<br>    padding-top: 5em;<br>    background: #222;<br>    border-top: 10px solid #000;<br>    color: white;<br>  }<br>}</pre><h3>Conclusion</h3><p>Keeping these principles in mind when writing CSS helps keep the code predictable and untangled. Additionally, by not mixing abstractions with details, classes become more re-usable, thus keeping your CSS files DRY. The benefit of of shorter and more predictable code is that problems are much easier to diagnose and fix completely rather than treat temporarily. Moreover, if everyone on the team implements SOLID principles when writing CSS, code review becomes much easier.</p><p>Below I provided a simplified example to highlight the concepts covered. To see something functional with HTML, <a href="https://codepen.io/mattricedev/pen/eWyvPe">check out this codepen</a>.</p><pre>// grid.scss</pre><pre>.container {<br>  display: flex;<br>  flex-wrap: wrap;<br>  align-items: flex-start;<br>  width: 100vw;</pre><pre>  &amp;.center {<br>    justify-content: center;<br>  }</pre><pre>  &amp;.space-between {<br>    justify-content: space-between;<br>  }<br>}</pre><pre>// services.scss</pre><pre>.container {<br>  &amp;.backdrop {<br>    background-color: #373737;<br>    color: #00D8FF;<br>  }</pre><pre>  &amp;.header {<br>    height: 5em;<br>    padding: 0 20px;<br>    &amp;.services {<br>      border-bottom: 10px solid #222;<br>    }<br>  }</pre><pre>  &amp;.body {<br>    &amp;.services {<br>      width: 40em;<br>      padding: 0 5vw;<br>      .column h2 {<br>        color: #00D8FF;<br>      }<br>    }<br>  }</pre><pre>  &amp;.footer {<br>    &amp;.services {<br>      border-top: 10px solid #222;<br>    }<br>  }<br>}</pre><h3>Sources and Further Reading</h3><ul><li>SOLID CSS, <a href="http://blog.millermedeiros.com/solid-css/](http://blog.millermedeiros.com/solid-css/)">http://blog.millermedeiros.com/solid-css/</a></li><li>SOLID Object Oriented Principles And CSS: Part 1, <a href="http://vanseodesign.com/web-design/solid-oo-principles-1/](http://vanseodesign.com/web-design/solid-oo-principles-1/)">http://vanseodesign.com/web-design/solid-oo-principles-1/</a></li><li>SOLID Object Oriented Principles And CSS: Part 2, <a href="http://vanseodesign.com/web-design/solid-oo-principles-2/](http://vanseodesign.com/web-design/solid-oo-principles-2/)">http://vanseodesign.com/web-design/solid-oo-principles-2/</a></li><li>The single responsibility principle applied to CSS, <a href="https://csswizardry.com/2012/04/the-single-responsibility-principle-applied-to-css/](https://csswizardry.com/2012/04/the-single-responsibility-principle-applied-to-css/)">https://csswizardry.com/2012/04/the-single-responsibility-principle-applied-to-css/</a></li><li>The open/closed principle applied to CSS, <a href="https://csswizardry.com/2012/06/the-open-closed-principle-applied-to-css/](https://csswizardry.com/2012/06/the-open-closed-principle-applied-to-css/)">https://csswizardry.com/2012/06/the-open-closed-principle-applied-to-css/</a></li><li>BEM 101, <a href="https://css-tricks.com/bem-101/](https://css-tricks.com/bem-101/)">https://css-tricks.com/bem-101/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a2f8439633c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/lunar-collective-blog/a-solid-solution-iii-9a2f8439633c">A SOLID Solution: Part III</a> was originally published in <a href="https://medium.com/lunar-collective-blog">Lunar Collective Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A SOLID Solution: Part II]]></title>
            <link>https://medium.com/lunar-collective-blog/a-solid-solution-ii-f30507a8b134?source=rss-e14be81a4854------2</link>
            <guid isPermaLink="false">https://medium.com/p/f30507a8b134</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[web-design]]></category>
            <category><![CDATA[css]]></category>
            <category><![CDATA[scss]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Matt Rice]]></dc:creator>
            <pubDate>Mon, 22 May 2017 14:07:08 GMT</pubDate>
            <atom:updated>2017-05-26T17:09:24.182Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4gGeIwtHOjZyQqdOWi8srA.jpeg" /></figure><p><a href="https://blog.lunarcollective.co/a-solid-solution-to-css-9f48f5663332">Having identified the issue in Part I</a>, we can now fix it. But more-so, we want to be able to identify when these problems will occur and stop them before they become something big and take unnecessary time fixing them. Therefore, this section and <a href="https://blog.lunarcollective.co/a-solid-solution-iii-9a2f8439633c">the next</a> aims to reflect on my mistakes and outline a system for writing CSS to prevent the mistakes from occurring again.</p><p>I looked through a few CSS methodologies to keep things organized. One is the <a href="https://css-tricks.com/bem-101/">Block, Element, Modifier (BEM) methodology</a>, which I think could be very useful when writing and organizing large CSS projects.</p><p>However, I wanted to find a more fundamental system that applies regardless of the preferred CSS methodology. What I found was the classic: SOLID principles. I covered these principles when learning Object Oriented languages. But I was curious to see how SOLID applied to CSS.</p><h3>Structuring Code and Classes</h3><p>I begin this discussion of SOLID around CSS file organization and code structure. For this, I focus on two principles. First, the Single Responsibility Principle which states that a class should have only a single responsibility. I abstract this a little more to speak both at the file level (organizing CSS files based on their purpose) as well as at the code level (separating css classes around their structural and functional purposes).</p><p>Second, I discuss the Liskov Substitution Principle which states objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program. I apply this in CSS as making sure that functionally similar classes are interchangeable. They should not carry extra baggage that could be extended in an additional class.</p><h4>Single Responsibility Principle</h4><p>As mentioned above, the Single Responsibility Principle (SRP) in CSS means we should separate structure from presentation. SRP is helpful when defining your site structure in CSS and also later when deciding whether or not to combine classes or keep them separate.</p><p>First, CSS classes should be organized into files based on which piece of the site they apply to. In my situation, we had a separate CSS file for most individual pages. In the case where several pages were nearly identical, we would put them into one file which included mixins to account for the distinctions between pages. In addition, we had separate CSS files that covered the general site structure as well as the even more fundamental grid system. Having such file separation is valuable in the same way any organization is valuable — it makes everything easy to find and understand.</p><p>I made the mistake of modifying my grid system outside of the grid file. By having .container defined in two separate files, I couldn’t quickly determine everything that the container block did or that it was problematic. Instead, any changes to .container should have occurred only in the .container class inside grid.scss.</p><p>Second, at the code level CSS classes should be separated based on whether they include structural or presentational properties. In my services file, I frequently mixed structural and presentational CSS within single classes. This bloated my CSS by making classes larger than they need to be and inhibited their re-usability. Because code wasn’t re-usable, I was more frequently repeating myself which made my code not DRY.</p><p>Practically speaking, however, I don’t think this principle is useful to do in every situation. While doing so makes CSS structure more predictable, it adds unnecessary organization that is just a little too much.</p><pre>// Before applying SRP<br>.container {<br>  &amp;.services-header {<br>    height: 5em;<br>    padding: 0 20px;<br>    border-bottom: 10px solid #222;<br>  }<br>}</pre><pre>// After applying SRP<br>.container {<br>  &amp;.services-header {<br>    &amp;.block {<br>      height: 5em;<br>      padding: 0 20px;<br>    }</pre><pre>    &amp;.style {<br>      border-bottom: 10px solid #222;<br>    }<br>  }<br>}</pre><p>See larger examples here:</p><p>- <a href="https://codepen.io/mattricedev/pen/jmYrOQ">Pre-SRP</a><br>- <a href="https://codepen.io/mattricedev/pen/LyeZPZ">Post-SRP with block/style distinction</a><br>- <a href="https://codepen.io/mattricedev/pen/rmpLOB">Post-SRP with extend</a></p><p>Adding this structure adds 4 extra lines. It’s not so bad, but when you’re doing it for every element, it gets unnecessarily bloated. Additionally, none of these blocks or styles are very re-usable.</p><p>Instead, I think SRP is used more to keep in mind that whenever you create structural classes, such as .flex-center, don’t mix in presentational properties. This is a bit more of an intuitive way to write CSS and allows the .flex-center class to be more re-usable. For example:</p><pre>.container {<br>  &amp;.header {<br>    height 5em;<br>    padding: 0 20px;<br>    border-bottom: 10px solid #222;<br>  }<br>  <br>  &amp;.flex-center {<br>    display: flex;<br>    justify-content: center;<br>  }<br>}</pre><p>While .header is probably not too re-usable, by making .flex-center completely structural, I can use it on any .container block where I find it necessary to add these flex properties.</p><h4>Liskov Substitution Principle</h4><p>Similar to SRP, the Liskov Substitution Principle (LSP) also points to keeping structural and presentational classes distinct. However, LSP is more-so focused consistency between similar child classes. According to this principle, objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program. In other words, classes that extend a base class in a similar way should be interchangeable. Let’s look at an example:</p><pre>// good<br>.flex {<br>  display: flex;<br>  &amp;.center {<br>    justify-content: center;<br>  }<br> <br>  &amp;.space-between {<br>    justify-content: flex-end;<br>  }<br>}</pre><pre>// bad<br>.flex {<br>  display: flex;<br>  &amp;.center {<br>    justify-content: center;<br>  }</pre><pre>  &amp;.space-between {<br>    justify-content: flex-end;<br>    padding: 20px;<br>    border-bottom: 5px solid teal;<br>  }<br>}</pre><p>In the ‘good’ example above, both .center and .space-between can be used interchangeably without one causing results that the other does not have. In the ‘bad’ example, .space-between adds extra stuff that is not inferred in the name or in the behavior of it’s sibling.</p><h3>To be continued…</h3><p>Next I continue the discussion of using SOLID principles in CSS by covering how to responsibly extend classes that we have already created. This discussion focuses on the Open/Close Principle, Interface Segregation Principle, and the Dependency Inversion Principle.</p><p><a href="https://blog.lunarcollective.co/a-solid-solution-iii-9a2f8439633c"><em>Continue to Part III.</em></a></p><h3>Sources and Further Reading</h3><ul><li>SOLID CSS, <a href="http://blog.millermedeiros.com/solid-css/](http://blog.millermedeiros.com/solid-css/)">http://blog.millermedeiros.com/solid-css/</a></li><li>SOLID Object Oriented Principles And CSS: Part 1, <a href="http://vanseodesign.com/web-design/solid-oo-principles-1/](http://vanseodesign.com/web-design/solid-oo-principles-1/)">http://vanseodesign.com/web-design/solid-oo-principles-1/</a></li><li>SOLID Object Oriented Principles And CSS: Part 2, <a href="http://vanseodesign.com/web-design/solid-oo-principles-2/](http://vanseodesign.com/web-design/solid-oo-principles-2/)">http://vanseodesign.com/web-design/solid-oo-principles-2/</a></li><li>The single responsibility principle applied to CSS, <a href="https://csswizardry.com/2012/04/the-single-responsibility-principle-applied-to-css/](https://csswizardry.com/2012/04/the-single-responsibility-principle-applied-to-css/)">https://csswizardry.com/2012/04/the-single-responsibility-principle-applied-to-css/</a></li><li>The open/closed principle applied to CSS, <a href="https://csswizardry.com/2012/06/the-open-closed-principle-applied-to-css/](https://csswizardry.com/2012/06/the-open-closed-principle-applied-to-css/)">https://csswizardry.com/2012/06/the-open-closed-principle-applied-to-css/</a></li><li>BEM 101, <a href="https://css-tricks.com/bem-101/](https://css-tricks.com/bem-101/)">https://css-tricks.com/bem-101/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f30507a8b134" width="1" height="1" alt=""><hr><p><a href="https://medium.com/lunar-collective-blog/a-solid-solution-ii-f30507a8b134">A SOLID Solution: Part II</a> was originally published in <a href="https://medium.com/lunar-collective-blog">Lunar Collective Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A SOLID Solution to CSS]]></title>
            <link>https://medium.com/lunar-collective-blog/a-solid-solution-to-css-9f48f5663332?source=rss-e14be81a4854------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f48f5663332</guid>
            <category><![CDATA[grid-system]]></category>
            <category><![CDATA[design]]></category>
            <category><![CDATA[scss]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[css]]></category>
            <dc:creator><![CDATA[Matt Rice]]></dc:creator>
            <pubDate>Mon, 22 May 2017 14:06:10 GMT</pubDate>
            <atom:updated>2017-05-26T17:09:51.914Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SKkkedxkFkk2qH0u8eSFyA.jpeg" /></figure><p>This blog post details the CSS issues I encountered while building several pages for a company website. It is split into three separate posts.</p><p>Part I discusses the mistakes I created and how not fixing them created larger problems that were much harder to identify and fix down the road. Part II and III discuss the use of SOLID principles as a way to organize and write code so that these mistakes are prevented. <a href="https://blog.lunarcollective.co/a-solid-solution-ii-f30507a8b134">Part II</a> discusses two SOLID principles related to structuring CSS files and classes. <a href="https://blog.lunarcollective.co/a-solid-solution-iii-9a2f8439633c">Part III</a> discusses three SOLID principles related to creating new classes to extend on what is already built.</p><h3>The Project</h3><p>My first story while working with Lunar Collective was to add individual service pages to the LC website strictly using HTML and CSS. The story involved creating a template for the service pages to keep a consistent structural theme between service pages.</p><p>In addition to keeping each service page consistent, I wanted to maintain some structural consistency within the entire site itself. Fortunately, the codebase I jumped into had a custom CSS grid defined. Therefore, I could build the new service pages by using the existing grid system to create new pages and maintain site-wide structural consistency.</p><pre>// grid.scss</pre><pre>.container {<br>  display: flex;<br>  flex-wrap: wrap;</pre><pre>  .column {<br>    &amp;.flex {<br>      flex: 1 0 auto;<br>      flex-basis: 40%;<br>    }</pre><pre>    &amp;.half {<br>      width: 49%;<br>    }</pre><pre>    &amp;.third {<br>      width: 32%;<br>    }<br>  }<br>}</pre><p><a href="http://j4n.co/blog/Creating-your-own-css-grid-system">Guide to creating your own CSS grid</a></p><h3>The Mistakes</h3><h4>Mistake #1: Modifying Abstract Classes</h4><p>After I began, I noticed structural changes I needed to make to the service pages. I needed to add a margin-top and some flex properties to a container block but I also wanted to limit it to only the area on the page that I was changing (as opposed to every container block on the site). To do so, I created a new class .services containing the margin and flex properties and appended it to .container, creating .container.services.</p><pre>// grid.scss</pre><pre>.container {<br>  display: flex;<br>  flex-wrap: wrap;<br>}<br><br>// services.scss</pre><pre>.container.services {<br>  margin-top: 40px;<br>  justify-content: center;<br>  align-items: center;<br>}</pre><p>So far so good (as will be explained later, this is a safe and proper way to extend core grid structure). I continued building the site with this in mind — create new, more specific classes to build upon the old, more general classes.</p><p>The mistake occurred when I decided to take a step back and refactor my CSS. I grew increasingly anxious as I soon had some HTML elements with 5 or more classes, each class having a particularly important structural, organizational, or presentational responsibility. I realized that almost all .container blocks needed the margin-top and flex properties in .services. So I decided to modify the core grid system, reduce .container.services down to .container, and add extensions to the fewer .container blocks that needed different properties.</p><pre>// grid.scss</pre><pre>.container {<br>  display: flex;<br>  flex-wrap: wrap;<br>  margin-top: 40px;<br>  justify-content: center;<br>  align-items: center;<br>}</pre><p>This doesn’t seem like a bad idea outright. However, more .container blocks than I accounted for were affected. This change also created some unpredictable behavior with other structural classes which relied on the original .container block. Specifically, every page’s header and footer were wrapped in a .container, leaving a nice 40px white gap immediately above them. This should be a quick and easy fix. <em>Should be</em>.</p><h4>Mistake #2: Modifying Abstract Classes in the Wrong File</h4><p>Rather than modifying .container in grid.scss, I modified .container in the .services.scss. So rather than the grid.scss as displayed immediately above, it looked more like this:</p><pre>// grid.scss</pre><pre>.container {<br>  display: flex;<br>  flex-wrap: wrap;<br>}</pre><pre>// services.scss</pre><pre>.container {<br>  margin-top: 40px;<br>  justify-content: center;<br>  align-items: center;<br>}</pre><p>Now the problem I created was split and hidden in two different locations. This mistake was partly due to not completely understanding the codebase and the importance of having a separate grid file. It was also partly due to the fact that I already had .container.services defined in services.scss and thought that by just deleting the .services class, I’d avoid tangling code up by moving stuff around. If the code was here before I deleted the class, it probably should stay here after I deleted the class. This was a bad decision.</p><p>Furthermore, because the CSS was in services.scss, I made the embarrassing assumption that only the service pages would be affected by my changes. As a result, this caused the changes to the main site to go unnoticed. Ideally, this would be caught in code-review. However, just by looking at the code it’s much harder to identify design problems. And the links I posted on the pull request to visually review the sight only focused on the service pages.</p><h4>Mistake #3: Modifying Abstract Classes in Wrong Files and then Patching the Now Broken Abstractions</h4><p>The problem got compounded the longer it took me to notice the problem. In general, the sooner you notice a problem, the more likely you can make a causal connection between the change and the problem and reverse it. However, if the problem occurs even a few minutes later you may have already made enough changes to not know its source.</p><p>Because the problem mostly manifested on pages I wasn’t actively monitoring, it took me a while to notice something larger was wrong. And because I didn’t notice something was larger wrong for a while, I added small bandages wherever it appeared. This was bad because by adding bandages, the problem was only getting treated rather than getting fixed. And unless the underlying problem is fixed, it may keep resurfacing (which it did), requiring more bandages to treat it (which it did).</p><p>Moreover, if the underlying problem is on a very general level block like a .container, each container will require some amount of treatment. In the end, the code is unnecessarily bloated, making it harder to find the source of the problem, and making it harder to fix the problem once it is finally identified.</p><p><a href="https://blog.lunarcollective.co/a-solid-solution-ii-f30507a8b134"><em>Continue to Part II.</em></a></p><h3>Sources and Further Reading</h3><ul><li><strong><em>Creating your own Grid System</em></strong>, <a href="http://j4n.co/blog/Creating-your-own-css-grid-system">http://j4n.co/blog/Creating-your-own-css-grid-system</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f48f5663332" width="1" height="1" alt=""><hr><p><a href="https://medium.com/lunar-collective-blog/a-solid-solution-to-css-9f48f5663332">A SOLID Solution to CSS</a> was originally published in <a href="https://medium.com/lunar-collective-blog">Lunar Collective Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Accessibility]]></title>
            <link>https://medium.com/@mattrice12/accessibility-6744476f41a1?source=rss-e14be81a4854------2</link>
            <guid isPermaLink="false">https://medium.com/p/6744476f41a1</guid>
            <category><![CDATA[jquery]]></category>
            <category><![CDATA[accessibility]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[rails]]></category>
            <dc:creator><![CDATA[Matt Rice]]></dc:creator>
            <pubDate>Mon, 20 Feb 2017 20:30:29 GMT</pubDate>
            <atom:updated>2017-04-24T15:11:31.485Z</atom:updated>
            <content:encoded><![CDATA[<p>As part of a code challenge, I was tasked with determining how to make an app accessible to users with physical or visual disabilities. I was to explain the best practices in Rails and jQuery using Aria attributes (the app I was making accessible was a Rails app using jQuery). First, I will explain what Aria attributes are and many of the best practices for implementing them into a simple app. Then, I will discuss how I would go about implementing Aria attributes into my app, which is a simple app with a textarea and output section.</p><h3>Aria</h3><h4>What it is</h4><p><a href="https://www.w3.org/WAI/intro/aria">Aria attributes</a> make content more navigable and understandable. They are added to HTML elements so that screen readers can pick them up and keyboard users can navigate to these elements. They especially help with dynamic content and advanced user interface controls developed with HTML, JavaScript, and related technologies.</p><h4>Aria Attributes and Best Practices</h4><p><strong>1. Default Semantics</strong><br>Before going into specific attributes, it is important to note than in HTML5 most elements have default semantics that are exposed to the browser and are read by screen readers. Default semantics just describe what the element is. For example, an <em>h1</em> has a heading role with a level 1 status (h2:heading, level 2). As a result, I do not need to manually set the h1’s role or level. Doing so is <a href="https://www.sitepoint.com/avoiding-redundancy-wai-aria-html-pages/">redundant</a> and <a href="https://w3c.github.io/aria-in-html/#aria-adds-nothing-to-default-semantics-of-most-html-elements">generally not advisable</a>. A benefit of writing good HTML is that you get a good amount of accessibility for free.</p><p>Contrarily, some elements like the <em>div</em> do not have such default semantics, and if I want to make it a heading, then I need to give it the role=”heading” attribute. Using roles are more often used on the <a href="http://vanseodesign.com/web-design/five-rules-aria-html/">non-specific</a>, <a href="http://stackoverflow.com/questions/22742066/aria-landmarks-not-working-in-textarea-input"><em>div</em>-like</a> elements.</p><p><strong>2. </strong><a href="https://www.w3.org/TR/WCAG20-TECHS/aria#ARIA11"><strong>Roles</strong></a><br>So what are roles anyways and why do we need them? Roles allow elements to serve as landmarks for the user. Landmarks help assistive technology users orient themselves to a page and helps them navigate easily to various sections of a page. As a user tabs through the page, the screen reader will announce the element’s role. This way, the user knows whether he or she tabbed to an element with a navigation role, a main role, a region role, a form role, or a different role. <a href="https://www.w3.org/TR/wai-aria/roles#roles_categorization">Here is a list of roles</a>.</p><p>The alert role role=”alert” is used to communicate an important and usually time-sensitive message to the user. When this role is added to an element, the browser will send out an accessible alert event to assistive technology products which can then notify the user about it. This is often helpful when <a href="https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/ARIA_Techniques/Using_the_alert_role">relaying a success or error message</a> to the user on form submission.</p><p><strong>3. Aria-live<br></strong>An alternative to setting an element’s role to alert is to set the region to aria-live=”assertive”. Both alert and aria-live work with a dynamic webpage/application and announce when that content changes. Aria-live has two settings polite and assertive — polite waits until the screen reader is finished with its current announcements; assertive interrupts its current announcements and gets announced immediately.</p><p><strong>4. </strong><a href="https://www.w3.org/TR/wai-aria/states_and_properties"><strong>Labels</strong></a><br>All form fields should have labels or some way for a screen reader to inform the user what the input field represents. Typically the developer would use aria-labelledby to connect the input to the label via the label’s id. aria-describedby is used for longer descriptions. aria-label is used when an input field has no associated label — e.g., the textarea in my app.</p><p><strong>5. </strong><a href="https://www.paciellogroup.com/blog/2014/08/using-the-tabindex-attribute/"><strong>Tabindex</strong></a><br>The tabindex attribute indicates that an element can be focused on, and determines how that focus is handled. A keyboard user will typically move through web content using the tab key, moving from one focusable element to the next in sequential order.</p><ul><li>tabindex=”0&quot; — When tabindex is set to 0, the element is inserted into the tab order based on its location in the source code.</li><li>tabindex=”+n” — A tabindex of 1 or greater imposes a custom tab order (lower numbers are tabbed to first).</li><li>tabindex=”-n” — Setting tabindex to -1 makes the element focusable but outside the tab order. This is useful for errors, which should be excluded from the tab order. The idea behind this that the user should be notified of errors (otherwise he might think the form is broken and leave), but the errors should be outside the tab order so they don’t interfere with the user navigating to the form.</li></ul><h3>My Changes</h3><h4>Overview</h4><p>To make my app accessible, I would do the following: First, I would make my app more dynamic so that I could take advantage of the role=”alert” attribute to announce whether the submission was successful or erroneous. Second, I would set tabindexes on several of the main elements (nav, headers, textarea) so that these main elements serve as landmarks and the page is easier to navigate for the user. Finally, I would add an aria-label attribute to the textarea with a brief of its purpose and its character limit, and I would change my heading elements to h1. I wouldn’t need to add any other roles since the default semantics for most of these elements take care of that. I discuss the WAIAble gem last, but I end up not using it because it doesn’t offer me anything that I can’t do easily (though it might be useful in larger apps).</p><p><strong>1. Live Regions / Alert</strong><br>To notify the user of erroneous or successful submissions, I would first make the content more dynamic, by using jQuery and AJAX for submission. Then I would set the element containing success/error messages to be live: aria-live=”assertive”. Alternatively, I could alert the user when there is a change: role=”alert”. Currently with my static page, the screen reader doesn’t recognize my error messages when they pop up. Even with the WAIAble gem (discussed below), the screen reader will only read the error in certain, limited situations).</p><p>I would also use jQuery to announce character limit information to the user. I would add $(char).attr(“role”, “alert”) when user types more than 500 characters. When the character count equals or drops below 500 characters, I use removeAttr(“role”, “alert”) to remove the attribute.</p><p><strong>2. Textarea</strong><br>To label my textarea, I would add the aria-label attribute with a custom description, such as “Type your vent here. Vents must be between 5 and 500 characters.” I do not need to add role=&quot;textbox&quot; since this is part of the textarea’s default semantics. I initially had autofocus=&quot;true&quot; on the textarea, but I decided to take it off. I referred to Facebook and Twitter, and realized it is pretty standard for a non-accessible user to select the textarea before typing. This solves the problem of starting with focus in the middle of the page rather than at the top. Thus a visually impaired user might not be so confused when first landing on the page.</p><p><strong>3. Heading elements / Aria-level<br></strong>Because heading elements have a default role=”heading”, I didn’t need to add the role attribute. However, because I initially had them as h2 elements for styling purposes, they had a heading level of 2. As a result, the screen reader announces my main sections as being in “heading level 2”, which makes it sound like a sub-section. I found this to be confusing, so I converted them to h1 elements. Alternatively, I could have kept my heading elements as h2 for styling purposes and set aria-level=”1&quot;. However, there really was no reason to prefer h2 over h1 for styling, so I was better off changing the HTML element to h1 and using its default semantics to announce the heading level. As mentioned above, good HTML gives you accessibility for free.</p><p><strong>4. Tabindex<br></strong>Because my page is structured in a weird order (the .content class has flex-wrap: wrap-reverse;), I need to specify the tabindexes for several elements, even ones that are already focusable. Since I want the instructions(.right-block) to be accessed before the form, I set the nav and .right-block to be tabindex=&quot;1&quot; and set everything in the left-block (including the tab-able elements in the form) to be tabindx=&quot;2&quot;. I also set my error list to tabindex=&quot;-1&quot; and added role=&quot;alert”. This way, the screen reader announces them, but they don’t interrupt the tab order.</p><p><strong>5. </strong><a href="https://github.com/techvision/waiable"><strong>WAIAble gem</strong></a><br>This gem allows the developer a shortcut to adding standard ARIA attributes to forms. In short, it connects inputs to their labels, converts error messages into links (making them accessible via tab), adds the aria-required=”true” to inputs when there is a model validation presence: true, and adds other notifiers when element attributes are present (such as announcing the size limitation when a maxlength is set to the input).</p><p>Unfortunately, because of the way I structured my app, some of these features in the WAIAble gem are not that relevant. Additionally, at this point it seems easier to just implement them manually.</p><ul><li>Because my textarea doesn’t have a label, WAIAble won’t add thearia-labelledby attribute to my textarea.</li><li>Because my app is (originally) mostly static and requires a refresh when submitting the form, screen readers won’t be able to read my error messages unless the user tabs to it. And if I switch to a more dynamic app, I want my errors to have a tabindex of “-1”, which makes WAIAble converting them into links obsolete.</li><li>The aria-required=”true” addition that comes with the WAIAble gem is pretty useful. I just set the validation presence: true in the model, and the gem adds an aria-required=”true” field to the textarea. However, adding a gem just to avoid typing aria-required=&quot;true&quot; is overkill.</li><li>I would not set a maxlength attribute on my textarea because I don’t want to limit the user from typing more than 500 characters; I just want to prevent the user from submitting it.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6744476f41a1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>