<?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 Jason Doggart on Medium]]></title>
        <description><![CDATA[Stories by Jason Doggart on Medium]]></description>
        <link>https://medium.com/@JasonCodes?source=rss-dc957c10099c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*akKGPWpSSj2vOlREQnOnrQ.jpeg</url>
            <title>Stories by Jason Doggart on Medium</title>
            <link>https://medium.com/@JasonCodes?source=rss-dc957c10099c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 05:20:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@JasonCodes/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Simple Modals in Ruby on Rails with MicroModal]]></title>
            <link>https://medium.com/@JasonCodes/simple-modals-in-ruby-on-rails-with-micromodal-f91165269ae2?source=rss-dc957c10099c------2</link>
            <guid isPermaLink="false">https://medium.com/p/f91165269ae2</guid>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[full-stack]]></category>
            <category><![CDATA[a11y]]></category>
            <category><![CDATA[micromodal]]></category>
            <category><![CDATA[modal]]></category>
            <dc:creator><![CDATA[Jason Doggart]]></dc:creator>
            <pubDate>Tue, 12 Feb 2019 18:03:42 GMT</pubDate>
            <atom:updated>2019-02-12T18:30:48.142Z</atom:updated>
            <content:encoded><![CDATA[<h3>Simple Modals in Ruby on Rails with Micromodal.js</h3><p>I recently completed a Ruby on Rails app that didn’t use a UI framework but needed modals. Rather than re-inventing the wheel, I opted to use <a href="https://micromodal.now.sh/">Micromodal</a> and loved it.</p><p>Micromodal is a lightweight, configurable and a11y-enabled modal library written in pure JavaScript.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xZoZPVuncLxHuXgHQCz0Tg.png" /><figcaption>Micromodal’s sample modal on their website. All modals come with built in accessibility.</figcaption></figure><p>This tutorial will show you how to install Micromodal and quickly get it running in your apps.</p><h3>Build a sample app</h3><p>Let’s start by building a simple app. I’ll be using Rails 5.2, which comes with the Webpacker gem built in. If you’re using an earlier version of Rails, you can always follow the installation for <a href="https://github.com/rails/webpacker">Webpacker</a>, and you’ll be all caught up with me.</p><p>Run the following command in your terminal:</p><p>Rails new simple-modal --webpack</p><p>Take note of the --webpack flag on our Rails new command. This tells Rails that we want to use Webpacker in this applicaiton.</p><p>After our app has been created, let’s cd into the directory.</p><p>cd simple-modal and open up a server to make sure we’re up and running: rails s</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F5hOvwyRmwnz8uPU6UlELA.png" /><figcaption>Good to go!</figcaption></figure><p>Since we’re just demonstrating modals here, we’ll just use some static pages. Let’s create our route:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bfefb3d9ec27886f68f1d0ba26555a6b/href">https://medium.com/media/bfefb3d9ec27886f68f1d0ba26555a6b/href</a></iframe><p>and our controller:</p><p>rails g controller static home</p><p>This command will create a new controller for us called StaticController with a single method called home. It will also create a view for this method. Let’s edit that view now.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/99dc04315c6ce5a05711c19993ff86ad/href">https://medium.com/media/99dc04315c6ce5a05711c19993ff86ad/href</a></iframe><p>And now our root page looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*s7jFgEvr6a51O7gDqHczRg.png" /></figure><p>Of course, that link does nothing yet. Time to change that.</p><h3>Adding Micromodal</h3><p>Since we have the Webpacker gem installed with our Rails app, adding Micromodal is as simple as following the installation directions on their site. In your terminal, type the following:</p><p>yarn add micromodal --save</p><p>Just like that, Micromodal is installed! Now we need to tell our rails app to include the Micromodal javascript in our asset pipeline. To this, we need to update our application.js file as so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/33a4a815b49f17c33ab7d92a02ec08a8/href">https://medium.com/media/33a4a815b49f17c33ab7d92a02ec08a8/href</a></iframe><p>Note that we’ve added the line:</p><p>//= require micromodal/dist/micromodal</p><p>This points our asset pipeline to the following javascript file:</p><p>./node_modules/micromodal/dist/micromodal.js</p><p>We’ll also use Jquery to initialize Micromodal. To do so, we’ll need to add the gem to our Gemfile. Add:</p><p>gem ‘jquery-rails&#39;, ‘~&gt;4.3&#39;, ‘&gt;= 4.3.3’</p><p>to your gemfile, then in your terminal, type:</p><p>bundle</p><p>Finally, update your application.js file by adding the following line right underneath //= require rails-ujs:</p><p>//= require jquery</p><h3>Initializing Micromodal</h3><p>Now that we’ve included Micromodal in our asset pipeline, we need to tell our application to use it. We do this by calling it in our Javascript file. Create a new Javascript file by typing the following into your terminal in the root directory of the app:</p><p>touch app/assets/javascripts/micromodal.js</p><p>Now open the file, and add the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6854009cdf16d992cc711fb8c42d8f02/href">https://medium.com/media/6854009cdf16d992cc711fb8c42d8f02/href</a></iframe><p>The above code uses Jquery to initialize Micromodal once the document is ready.</p><h3>Updating our view</h3><p>Okay, we’ve got Micromodal installed and wired up. Let’s start using it!</p><p>Micromodal comes with no styling at all, which is a bit underwhelming. To make things a bit prettier, we’ll use one of their recommended styling guides, which they link to at the bottom of their page.</p><p>We’ll add the modal to our view template:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2427e7d2cd4126424eb98cc00cacfc92/href">https://medium.com/media/2427e7d2cd4126424eb98cc00cacfc92/href</a></iframe><p>Micromotion does a great job on their site of outlining what is required to have functioning modals. I’d highly recommend you read through their Usage section to understand what each data attribute, aria, and id contributes to the modal.</p><p>Now, our page looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tdsz6bvEpFxF5BlVT4tZ6w.png" /><figcaption>Not what we want!</figcaption></figure><p>This isn’t what we want. Our modal is always showing up, and it’s ugly. Let’s add some CSS to fix all of this. Create a new CSS file by typing the following into your terminal:</p><p>touch app/assets/stylesheets/micromodal.css</p><p>Now, add the following style rules to this file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b9bd62dbedbff7eaf4b743211e7c80e3/href">https://medium.com/media/b9bd62dbedbff7eaf4b743211e7c80e3/href</a></iframe><p>This hides our modal, but our button still isn’t wired up to trigger the modal. Add data-micromodal-trigger=&quot;modal-1&quot; to the button tag in our view template.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ulXpEMnTS0V1fORoE0V18w.png" /><figcaption>Now THAT’s more like it!</figcaption></figure><p>And there you go! If you’re looking for the code to this app, you can find the whole repository here:</p><p><a href="https://github.com/jasondoggart/simple-modal">jasondoggart/simple-modal</a></p><p>Happy hacking!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f91165269ae2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Helpful Rails Tutorials]]></title>
            <link>https://medium.com/series/helpful-rails-tutorials-1281c74fa12e?source=rss-dc957c10099c------2</link>
            <guid isPermaLink="false">https://medium.com/p/1281c74fa12e</guid>
            <dc:creator><![CDATA[Jason Doggart]]></dc:creator>
            <pubDate>Mon, 14 May 2018 15:38:56 GMT</pubDate>
            <atom:updated>2018-05-24T16:53:06.210Z</atom:updated>
            <content:encoded><![CDATA[<p>The Ruby on Rails community is full of incredible people who’ve provided amazing resources.</p><p>I’ve decided to begin to document some of the great resources and tutorials I’ve used as I’ve been learning. This serves as a resource for me (so I’m not googling for the same tutorial I’ve read through 100 times), and hopefully for others.</p><p><a href="https://www.railstutorial.org/book/beginning">Michael Hartl’s “The Ruby on Rails Tutorial”</a> is where I started, and it’s often where I go when a concept slips my mind.</p><p>If you’re starting out with Rails, I’d encourage you to work this tutorial (especially chapter 3 to the end) 3 or more times. Each time I worked through this I learned more, and the things I had previously learned sank in deeper.</p><p>I’ve read through a LOT of beginner tutorials on Rails, and nothing has come close to this in terms of depth of coverage and ease of entry for those new to web development.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/364/1*riH7ZxYI0wplmujdJ_ydNg.jpeg" /></figure><p>Speaking of Michael Hartl, his <a href="https://www.learnenough.com/">Learn Enough Society</a> is full of incredible tutorials. If you’re new to software development, he has everything you need.</p><p>His tutorials get you to a level of understanding such that you can get value out of the higher-level content on almost anything. Highly recommended!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/1*5KRrg-jnZliXepYsZ3oKMA.jpeg" /></figure><p>Another great Rails resource — Daniel Kehoe’s <a href="https://tutorials.railsapps.org/">Capstone Rails Tutorials</a>.</p><p>Daniel offers a paid course (either monthly access or a one time fee), which provides access to some really practical tutorials, including:</p><ul><li>Using Devise (a popular authentication gem)</li><li>Using rspec (a testing framework)</li><li>Role-based authorization (using Pundit)</li><li>Integrating Bootstrap into your apps</li></ul><p>Overall, this course has lots of great resources for those starting to build their own apps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/1*hWi3qS4ht4RS0kJ78dIRlg.png" /></figure><p>This isn’t a Rails resources, but still useful for any web developer.</p><p>Free code camp offers a full online bootcamp — all for free! Not are the courses tremendously valuable, but the community and blogs are great!</p><p>This is a great course for introductions to HTML, CSS, JS, Jquery, along with JavaScript backend technologies like node.js, express.js, and even visualizations like D3.</p><p>Overall, tons and tons and tons of resources!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*MibjuFPCUOL_K0wt68Xdfg.jpeg" /></figure><p><a href="https://thoughtbot.com/upcase/">Upcase is a ‘finishing school’ </a>put out by the great people at thoughtBot. Upcase provides a series of ‘trails’ focusing on various aspects of software development. These are screencasts that you can follow along to — a great way to not only learn but also to see great developer’s workflows. Some of the topics include:</p><ul><li>Test Driven Development</li><li>Vim</li><li>Intermediate Ruby on Rails</li><li>Design for developers</li><li>Mastering the shell</li><li>Any many more.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/168/1*J7Py5dW4_2Hb83QIqmV7rQ@2x.jpeg" /></figure><p>Practical Object Oriented Design in Ruby is a fantastic book written by Sandi Metz. If you haven’t yet, find all the interviews she’s given and listen to them.</p><p>This book is accessible, but full of great insight into the best ways to approach object oriented design. If you’re coming from some of the beginner Rails tutorials, this fills in a lot of the gaps in computer science you may feel like you have.</p><p>I loved it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1281c74fa12e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ruby on Rails — Importing from Excel]]></title>
            <link>https://medium.com/@JasonCodes/ruby-on-rails-importing-from-excel-1504fd99a35e?source=rss-dc957c10099c------2</link>
            <guid isPermaLink="false">https://medium.com/p/1504fd99a35e</guid>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[activerecord]]></category>
            <category><![CDATA[excel]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <dc:creator><![CDATA[Jason Doggart]]></dc:creator>
            <pubDate>Fri, 11 May 2018 16:23:21 GMT</pubDate>
            <atom:updated>2018-05-11T16:23:21.368Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*ssok7XOGoMImwP2iXZGyIQ.jpeg" /></figure><p>I’ve previous written about <a href="https://medium.com/@JasonCodes/ruby-on-rails-exporting-data-to-excel-b3b204281085">exporting your data from rails into an Excel file</a>. This time, I’ll be addressing how to allow your users to update and modify this spreadsheet, then upload and implement those changes in your app.</p><p>I’ll be continuing to use the same app as the last example. If you want to get up to speed, check out the repo <a href="https://github.com/jasondoggart/inventory">here</a>. Clone that repo, and then let’s go!</p><h3>Setup</h3><p>We’ll be using the roo gem to handle the heavy lifting of importing from Excel. Roo lets you import a variety of filetypes — we’ll address how to handle them later. For now, let’s add the following to our gemfile:</p><pre><em>#Gemfile</em></pre><pre>...<br>gem &quot;roo&quot;, &quot;~&gt; 2.7.0&quot;<br>...</pre><p>and install the gem:</p><pre>bundle</pre><p>Great!</p><p>Now, let’s add a link to import a spreadsheet to our index page:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/17c0e0294a64df6005bc5b25371ce935/href">https://medium.com/media/17c0e0294a64df6005bc5b25371ce935/href</a></iframe><p>This gives us an error, since we don’t have that route defined yet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ld0vjZ5IJXkHVNDj2aGv5w.png" /><figcaption>We need a route!</figcaption></figure><p>Let’s create the route:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/308f4ea6ddf3315f6b6163957e8732e1/href">https://medium.com/media/308f4ea6ddf3315f6b6163957e8732e1/href</a></iframe><p>Which now lets us load our page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nV1rdgMiXdPDLQ7gO0XgiA.png" /></figure><p>However, as soon as we click our new link, we’ll see our new error: unitialized constant ItemsImportController.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h2RGcMgGKrM9GlnpRFlCIQ.png" /></figure><p>So, let’s create it. In the terminal, we type:</p><pre>rails g controller items_imports new create</pre><p>Note that I’ve gone ahead and created our new and create actions, as I know I’ll need them shortly. With our controller created, we now can get to our new items_import page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mK3p0xHIcIk3cS0fWp-8Rg.png" /></figure><p>In our controller, we need to instantiate our items_import variable. However, in this case we don’t have a model to persist to the database — there is no ItemsImport object right now.</p><p>We could likely add the logic for handling the import in the Items model, but this would clutter up our model with methods it shouldn’t need to know about. In thoughtBot’s Upcase course “Intermediate Rails 5”, Matthew Mongeau talks about the single responsibility principal — where each object should have one task. We’ll try to follow this advice here.</p><p>So, to handle our import, we’ll create a new object, and store it in our models file.</p><pre>touch app/models/items_import.rb</pre><p>We’ll add the following to this object — I’ll unpack everything after showing you the final code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3014ee6f4620bb0ddc82ae77bb27af1e/href">https://medium.com/media/3014ee6f4620bb0ddc82ae77bb27af1e/href</a></iframe><p>Okay, that’s a lot of code! Let’s get through it so we’re on the same page.</p><p>First, we declare our class ItemsImport. Note that per rails conventions, this name matches the file name we’ve given it (items_import), but in PascalCase.</p><p>Next we include ActiveRecord::Model. By including this, we have access to ActiveRecord validations, which will let us make sure any changes that have been made in the spreadsheet are valid.</p><p>include &#39;Roo&#39; allows us to use all the functionality we get with the Roo gem.</p><p>attr_accessor :file will give us access to params[:items_import][:file] throughout the object.</p><p>Okay, getting into a bit more meat now.</p><pre>def initialize(attributes={})<br>  attributes.each { |name, value| send(&quot;#{name}=&quot;, value) }<br> byebug<br>end</pre><p>This method initializes our method with a hash of attributes. If no attributes are passed to it when it’s instantiated, then an empty hash is used. This would be the case in our new action in our controller, where we would call @items_import = ItemsImport.new.</p><p>If we instantiate the object with attributes, as we would during the create action, then each attribute passed to the object is parsed by its name and value. The name of the attribute is send back to the ItemsImport object, along with the value of the object.</p><p>This was a bit tricky for me. The ruby send method takes at least one argument, which must equal the name of a method in the object inheritance tree. In our case, we’re passing in params[:items_import], which includes the [:file] attribute. Since we’ve included the attr_accessor :file call in the object, this code sets the :file attribute in our object equal to the value of params[:items_import][:file].</p><p>That’s a mouthful.</p><p>On a lighter note, the next method is pretty straight-forward.</p><pre>def persisted?<br>  false<br>end</pre><p>This method tells rails that this object has no related table in our database.</p><p>The last few methods have been used to setup our object. Now we get into the meat of importing the spreadsheet.</p><pre>def open_spreadsheet<br>  case File.extname(file.original_filename)<br>  when &quot;.csv&quot; then Csv.new(file.path, nil, :ignore)<br>  when &quot;.xls&quot; then Roo::Excel.new(file.path, nil, :ignore)<br>  when &quot;.xlsx&quot; then Roo::Excelx.new(file.path)<br>  else raise &quot;Unknown file type: #{file.original_filename}&quot;<br>  end<br>end</pre><p>Here we look at our :file attribute, and see if we can use it to open a spreadsheet using Roo. We use a case statement to that takes in the file extension, and selects an appropriate action for opening the spreadsheet.</p><p>Note that in the case where our user uploads a CSV file, we simply use Rails’ native CSV tools. Note also that we’re getting our original_filename from our file attribute, which we instantiated in our send method.</p><p>Note that in order to import our data, we had to make two small changes to the index.xlsx.axlsx file we created in the last tutorial. We’re going to use this function to create a hash of key-value pairs, where the keys are the same as our attributes in the Item model. To make this hash, we need these attributes in our spreadsheet.</p><p>In addition, we also need our spreadsheet to include the id attribute for each item. This will allow us to use ActiveModel’s find_by_id method to look up the existing Item in our database, and update it as required.</p><p>The new index.xlsx.axlsx file is shown here:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f335a596380d51c9c662aa2f7129d10/href">https://medium.com/media/1f335a596380d51c9c662aa2f7129d10/href</a></iframe><pre>def load_imported_items<br>  spreadsheet = open_spreadsheet<br>  header = spreadsheet.row(5)<br>  (6..spreadsheet.last_row).map do |i|<br>    row = Hash[[header, spreadsheet.row(i)].transpose]<br>    item = Item.find_by_id(row[&quot;id&quot;]) || Item.new<br>    item.attributes = row.to_hash<br>    item<br>  end<br>end</pre><pre>def imported_items<br>  <a href="http://twitter.com/imported_items">@imported_items</a> ||= load_imported_items<br>end</pre><p>Our load_imported_items method first creates a new spreadsheet using our previously defined open_spreadsheet method. Next, we set a variable header to be equal to the the cells in the fifth row of our spreadsheet. Ruby stores this as an array.</p><p>Next, our method runs Ruby’s map function over a range from 6 (the first row of data in our spreadsheet) to the last_row of data. In this map block, there are a few steps to get our data into a format that Rails can use it.</p><p>First, we create a hash of the data in the current row. This has is created by making a two dimensional array [header, spreadsheet.row(i)]. We then use the transpose method to convert this into an array with two columns and a number of rows equal to the number of items in both header and spreadsheet.row(i). The first column in this new array is equal to the header name, and the second is equal to the corresponding value. So in our case, this would look something like:</p><pre>[<br> id, 1<br> name, &#39;Blue Level&#39;<br> quantity, 36<br>]</pre><p>By passing this array to Ruby’s Hash method, we set our row variable equal to a hash with keys equal to our model attributes, and values equal to their corresponding value. Pretty neat!</p><p>Our next line sets our item variable by either looking up the corresponding Item (by the id value stored in our row variable), or creating a new item if the id doesn’t existing in our database. This is pretty neat, because it allows our users to not only update existing items, but also to add new items. If no id is present in the spreadsheet when it’s uploaded, Rails will just create a new record with the other attributes (name and quantity) for us!</p><p>Once we’ve either found our Item or created a new one, we set its attributes to the attributes found in our row variable (which came from the uploaded spreadsheet).</p><p>Finally, we return the item variable. Using the map method, Ruby ultimately returns an array of items with a length equal to the number of items in the spreadsheet. Pretty cool!</p><p>We can now create a new method called imported_items which sets an instance variable for us to use by calling load_imported_items.</p><pre>def save<br>    if imported_items.map(&amp;:valid?).all?<br>      imported_items.each(&amp;:save!)<br>      true<br>    else<br>      imported_items.each_with_index do |item, index|<br>        item.errors.full_messages.each do |msg|<br>          errors.add :base, &quot;Row #{index + 6}: #{msg}&quot;<br>        end<br>      end<br>      false<br>    end<br>  end</pre><p>The last method in this object is the save method. Let’s unpack this one.</p><p>We’re using this method to see if the changes we made in our spreadsheet are valid, and if they are, to save them. If they’re not valid, we want to add error messages to indicate to the user where they’ve gone wrong.</p><p>To check if our items are valid, we map over our imported_items by calling &amp;:valid? on each of them. If this syntax is new to you (as it was for me), there’s a great explanation <a href="https://www.brianstorti.com/understanding-ruby-idiom-map-with-symbol/">here</a>. Suffice to say, it calls ActiveModel’s validations on each item, which will return either true (valid) or false (not valid). This map method returns an array of boolean values, which we then call .all? on. all? will return true if no values in the array are false or nil.</p><p>So, if all of the changes we made are valid, we return true, and call imported_items.each(&amp;:save!), which saves the items to our database. We then return true to allow whatever is calling this method that everything was saved.</p><p>If any of our changes are not valid, we use loop over each item and add all of the full_messages of each items errors to our imported_items variable.</p><p>We then return false to let the calling method know that save failed.</p><p>Wow! That was a lot to get through! Luckily, there’s isn’t much more before we’re done. Stay with me — we’re almost there!</p><p>Let’s update our controller to create a new ItemsImport object:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1dd9a33c08b38e01718e112295a735e0/href">https://medium.com/media/1dd9a33c08b38e01718e112295a735e0/href</a></iframe><p>Note that along with our new method, we’ve also added our create method. Our new method creates a new ItemsImport object. We’ll discuss the create method once we’ve looked at the items_imports form. In app/views/items_imports/new.html.erb, let’s add our form:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e963f8fe0f43c89a1d00130123ba2af9/href">https://medium.com/media/e963f8fe0f43c89a1d00130123ba2af9/href</a></iframe><p>This view is also good for providing your user with any information they need to successfully import the Excel file.</p><p>Our template is fairly straight-forward. We have a form_for, and in that form we have a file_field for :file. The user can select the file, then upload it.</p><p>On upload, Rails invokes the create action of the items_imports_controller, and passes it the params for @items_import, which contains only :file. Our controller then instantiates a new ItemsImport with this file, and tries to save it (which calls the save method we went through above. On a successful save, the controller will redirect_to the items_path. If the save is not successful, the controller will render the :new template, where the user will be presented with the errors that stopped the import from proceeding.</p><p>To see our error reporting in action, let’s update our items model to require the :name attribute:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/61fae9e82f55b435bd9667dcc3db499e/href">https://medium.com/media/61fae9e82f55b435bd9667dcc3db499e/href</a></iframe><p>Now, if we delete the name of our first item (while leaving the id and the quantity alone), we’ll see:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1hIZT3slOS_E-sgiU7WA_w.png" /></figure><p>Which is exactly what we want. And, if we leave everything alone, we’ll see it work. For instance, we can update our quantity of ‘Green America’ coffee to 1500, and see the change reflected after the update:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g8prwu5XJ7W7UB0zoPN8DQ.png" /><figcaption>Perfect!</figcaption></figure><p>So there you have it! I know this was a lot to get through, but hopefully it’s made sense to you. If you know of better ways to do this, or have any questions, feel free to get in touch in the comments.</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1504fd99a35e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ruby on Rails — Exporting Data to Excel]]></title>
            <link>https://medium.com/@JasonCodes/ruby-on-rails-exporting-data-to-excel-b3b204281085?source=rss-dc957c10099c------2</link>
            <guid isPermaLink="false">https://medium.com/p/b3b204281085</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[excel]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <dc:creator><![CDATA[Jason Doggart]]></dc:creator>
            <pubDate>Mon, 07 May 2018 17:26:10 GMT</pubDate>
            <atom:updated>2018-05-07T18:01:22.930Z</atom:updated>
            <content:encoded><![CDATA[<p>Often my applications will require data from my app’s database to be exported to Microsoft Excel. This may be required for a number of different reasons — client reporting tools, data analysis that occurs outside the scope of our app, or even because some clients are more comfortable digesting data in tools their familiar with (have you met an engineer who didn’t love Excel?).</p><p>Whatever the reason, data export to excel can be accomplished fairly easily using standard Rails tooling and some help from the <a href="https://github.com/straydogstudio/axlsx_rails">axlsx_rails</a> gem. In this walk-through, we’ll build an inventory app that allows users to export the contents of the store’s inventory to Excel.</p><p>Let’s get started. We’ll be using Rails 5.1 and Ruby 2.5 throughout.</p><h3>Setting it up</h3><p>First, let’s create the app:</p><pre>rails new -T -d postgresql<br>cd inventory</pre><p>In the above command I’ve include a couple flags:</p><ul><li>-T asks rails to skip installing the default test suite. While we won’t be using tests in this tutorial, I typically use rspec, which I would normally install after initializing the app</li><li>-d postgresql lets rails know that I want to use post postgresql as my database. I often deploy using Heroku, and Heroku uses postgresql by default. Using the same database during development reduces the risk of potential conflicts during deployment.</li></ul><p>Now that we’ve created our app, let’s start up the server and make sure everything’s working as expected:</p><pre>rails s</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UmHUvNjW09Uh6b7CS0qQwA.png" /><figcaption>Yay!</figcaption></figure><p>Okay, let’s start building our application. To help us get up to speed quickly, we’ll scaffold together an items resource:</p><pre>rails g scaffold item name:string quantity:integer</pre><p>Next let’s create our database and run the migration generated by rails:</p><pre>rails db:create<br>rails db:migrate</pre><p>Now, let’s point our root_path towards the index action of the items controller:</p><pre><em>#config/routes.rb</em></pre><pre>Rails.application.routes.draw do<br>  resources :items</pre><pre>  root to: &#39;items#index&#39;<br>end</pre><p>Now when we visit localhost:3000, we see:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gUEiTZ251ih6zxStys2sDA.png" /><figcaption>The newly created items index</figcaption></figure><p>To get some items inside our app, let’s create a seed file. We’ll use the Faker gem to create a bunch of different coffees in our inventory. First, let’s add Faker to our gemfile. You can always find the latest version of the gem at <a href="https://rubygems.org/gems/faker/versions/1.6.6">RubyGems.org</a>.</p><pre>#<em>Gemfile</em></pre><pre>...<br>gem &#39;faker&#39;, &#39;~&gt; 1.6&#39;, &#39;&gt;= 1.6.6&#39;<br>...</pre><p>Then run bundle to update our app:</p><pre>bundle</pre><p>Next, we’ll update our seeds.rb:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e93c0df5274defe32096147bd8cf1f74/href">https://medium.com/media/e93c0df5274defe32096147bd8cf1f74/href</a></iframe><p>Then we seed the database:</p><pre>rails db:seed</pre><p>And now if we refresh our app, we see 100 different blends of coffee:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hg6JfXNt0yjYMsw8UXSDOw.png" /><figcaption>That’ll wake you up!</figcaption></figure><p>Okay, we’ve got our data, now let’s get into exporting to Excel.</p><h3>Exporting to Excel</h3><p>In order to get our data exported to Excel, we’re going to use the <a href="https://github.com/randym/axlsx">axlsx gem</a>. Axlsx is an incredible gem, which allows you to “create excel worksheets with charts, images (with links), automated and fixed column widths, customized styles…”, all using ruby.</p><p>To access this gem in rails, we’ll be making use of the <a href="https://github.com/straydogstudio/axlsx_rails">axlsx_rails gem</a>, which provides great integration into rails.</p><p>Let’s get started.</p><p>In our gemfile, let’s add the following gems (as instructed in the readme):</p><pre><em>#Gemfile</em></pre><pre>...</pre><pre>gem &#39;rubyzip&#39;, &#39;&gt;= 1.2.1&#39;<br>gem &#39;axlsx&#39;, git: &#39;https://github.com/randym/axlsx.git&#39;, ref: &#39;c8ac844&#39;<br>gem &#39;axlsx_rails&#39;</pre><pre>...</pre><p>and install the new gems via bundler:</p><pre>bundle</pre><p>Finally, we need to restart our server so that it’s initialized properly with these changes:</p><pre>rails s</pre><p>Now we’re ready to start creating our spreadsheet. Let’s add a link to download the spreadsheet to our index page:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a0c74e29b4d446488b17668a61f5909d/href">https://medium.com/media/a0c74e29b4d446488b17668a61f5909d/href</a></iframe><p>Pay attention to the format: :xlsx included with the path. This tells our controller which format to provide back to the user.</p><p>This won’t work yet, though, because we haven’t told our controller what to do with a request for the xlsx format. Let’s fix that now. In our items controller, update the index method as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/def4bb842cd73ee4b9ff3bf5bcf6a520/href">https://medium.com/media/def4bb842cd73ee4b9ff3bf5bcf6a520/href</a></iframe><p>We still have one final piece missing: the template for our new spreadsheet. When we call a format of xlsx, the axlsx_rails gem will instruct our app to look for a file with the same name as the controller action (‘index’) with a file extension of ‘.xlsx.axlsx’.</p><p>Let’s create that file now:</p><pre>touch app/views/items/index.xlsx.axlsx</pre><p>We can now edit this file. I’ve shown the final file here — we’ll unpack it below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/04d779f70fcfa23e80e59e0f37ae7466/href">https://medium.com/media/04d779f70fcfa23e80e59e0f37ae7466/href</a></iframe><p>Ok, let’s take that apart a bit:</p><pre>wb = xlsx_package.workbook</pre><p>This line creates a variable (wb) that’s associated with a new workbook.</p><pre>wb.add_worksheet(name: &quot;Items&quot;) do |sheet|</pre><p>This line adds a new worksheet to our newly created workbook, then sends it a block of code for execution. We also name the new worksheet (creatively, “Items”).</p><pre>sheet.add_row [&quot;Item Name&quot;, &quot;Quantity&quot;]</pre><p>Here, we add the first row of data to our new worksheet. In this case, we’re adding the two attributes of our model, Item Name and Quanity. add_row accepts an array, with each item in the array representing the data of a single cell.</p><pre><a href="http://twitter.com/items">@items</a>.each do |item|<br>  sheet.add_row [item.name, item.quantity]<br>end</pre><p>Finally, we add all of our data. Note that helpfully all instance variables created in our controller action are available to us in this template. It’s simply a matter of iterating over each item in @items and showing the corresponding name and quantity.</p><p>Now, when we click our link, we download a new spreadsheet with all of our data!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_KjDFMG4dNBOmnwfc9IXxw.png" /><figcaption>Pretty neat!</figcaption></figure><p>Of course, it’s not pretty yet. Fortunately, the API provided by axlsx is incredible, and allows for a huge amount of customization. We’ll play with a little bit of styling to give you a taste of what’s possible, but I’d encourage you to glance through the <a href="https://www.rubydoc.info/github/randym/axlsx/Axlsx">docs</a> to how wide open this really is.</p><p>Let’s add a title, a date, and add some styling to the header row:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f53c5ee4f7e8f72aff3a187ed1d24732/href">https://medium.com/media/f53c5ee4f7e8f72aff3a187ed1d24732/href</a></iframe><p>Here we’ve added some styling options. You’ll see that for the project heading, we’ve added the options of b:true (bold) and sz: 14 (size 14). We’ve also added the date that the spreadsheet was downloaded (if you don’t recognize the strftime syntax, read up on it <a href="https://apidock.com/ruby/DateTime/strftime">here</a>. Finally, we bolded the column headings. The final result looks something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0usQy_PCl1VhFH-hct0oRg.png" /><figcaption>Looking prettier!</figcaption></figure><p>And there you go! You can now export your data to excel!</p><p>You can see the whole project on GitHub:</p><p><a href="https://github.com/jasondoggart/inventory">jasondoggart/inventory</a></p><p>Do you have a better way of doing something? Have some ideas for improvement? Or do you want some clarification? Hit me up in the comments, I’d love to hear from you!</p><p>Up next — how to edit this spreadsheet, then import the changes (and new items) back into our database.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b3b204281085" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>