<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="4.4.1">Jekyll</generator><link href="https://zacbaston.com/feed.xml" rel="self" type="application/atom+xml" /><link href="https://zacbaston.com/" rel="alternate" type="text/html" /><updated>2026-06-06T04:27:03+00:00</updated><id>https://zacbaston.com/feed.xml</id><title type="html">Zac Baston</title><subtitle>Building</subtitle><entry><title type="html">How I Learn from Code Tutorials</title><link href="https://zacbaston.com/how-to-learn-from-a-tutorial/" rel="alternate" type="text/html" title="How I Learn from Code Tutorials" /><published>2018-10-11T00:00:00+00:00</published><updated>2018-10-11T00:00:00+00:00</updated><id>https://zacbaston.com/how-to-learn-from-a-tutorial</id><content type="html" xml:base="https://zacbaston.com/how-to-learn-from-a-tutorial/"><![CDATA[<p>So you want to learn a thing about your favorite, new technology? For me, this often leads to googling a general phrase to begin with which points me towards a bunch of tutorials. Then I have to look through these tutorials quickly to determine which ones hold the most value for my goal.</p>

<ol>
  <li>
    <p>Quickly skim the content but only pay attention to the code samples. This is an opportunity to filter tutorials that are teaching you something you already know and also a chance to read someone else’s code. If you have determined you should continue forward, move to the second step. However, you may read through the code and realize “Oh, I’ve done this before.” If that’s the case, skip the next two steps and move on to the next tutorial.</p>
  </li>
  <li>
    <p>Now read through the text content of the post to try and understand what is being built without thinking about the code a whole lot. Here the focus is trying to understand the “what” and “why” questions about this technology. At this point you’ve read the code and then read the content of the article separately, so you should have a decent idea of what is being built so you are ready to proceed.</p>
  </li>
  <li>
    <p>The final step is a big one but starts with leaning back in your chair and cracking your knuckles. Now build out the example. You may not know exactly what’s going on but you have a good idea. This is where the fun happens since you get to make connections from A to B!</p>
  </li>
</ol>

<p>If you’re anything like me, you will fudge something up. I think it has to do with not wanting to simply copy-pasta examples which leads to errors. Hopefully these errors are easy to identify since it’s often some syntax issue. The other fun opportunity is that code is often not complete or there are assumptions made by the authors about certain versions, environment, etc. Due to this, you will encounter even more error messages! Each of these is an opportunity to learn more!</p>

<p>Eventually you will complete the tutorial. Hooray, you learned a thing! While you may not be an expert at that thing yet, you are better off than where you started and that’s all that matters when it comes to learning.</p>]]></content><author><name></name></author><summary type="html"><![CDATA[So you want to learn a thing about your favorite, new technology? For me, this often leads to googling a general phrase to begin with which points me towards a bunch of tutorials. Then I have to look through these tutorials quickly to determine which ones hold the most value for my goal.]]></summary></entry><entry><title type="html">Beginner Go Resources</title><link href="https://zacbaston.com/beginner-go-resources/" rel="alternate" type="text/html" title="Beginner Go Resources" /><published>2018-02-14T00:00:00+00:00</published><updated>2018-02-14T00:00:00+00:00</updated><id>https://zacbaston.com/beginner-go-resources</id><content type="html" xml:base="https://zacbaston.com/beginner-go-resources/"><![CDATA[<p>I’ve been learning Go for a couple of months and have accumulated a ton of bookmarks and links on the subject. Recently I decided to prune through those and figure out which ones I found the most helpful when getting started. Below are some of my favorites that helped me in a wide variety of topics from completely getting started, to understanding some of the more complex topics specifically related to the most powerful features of Go.</p>

<h2 id="metaresource">Metaresource</h2>

<p><a href="https://github.com/avelino/awesome-go">Awesome Go Github Repo</a></p>

<p><a href="https://golangweekly.com/">Golang Weekly</a></p>

<h2 id="general">General</h2>

<p><a href="https://golang.org/ref/spec">The Go Programming Language Specification</a></p>

<p><a href="https://golang.org/doc/effective_go.html">Effective Go</a></p>

<p><a href="https://medium.com/go-walkthrough">Go Walkthrough</a> (deep dive into a few of Go’s standard libraries)</p>

<p><a href="https://blog.gopheracademy.com/">Gopher Academy</a> (great blog series for a wide range of topics)</p>

<p><a href="https://peter.bourgon.org/go-best-practices-2016/">Go Best Practices 6 Years In</a></p>

<h2 id="beginner">Beginner</h2>

<p><a href="https://dave.cheney.net/resources-for-new-go-programmers">Resources for New Go Programmers - Dave Cheney</a> (Dave’s blog has tons of great info here and he actually spoke at the most recent Seattle Gopher meetup)</p>

<p><a href="http://devs.cloudimmunity.com/gotchas-and-common-mistakes-in-go-golang/">50 Shades of Go: Traps, Gotchas, and Common Mistakes for New Golang Devs</a></p>

<h2 id="screencaststutorials">Screencasts/Tutorials</h2>

<p><a href="https://www.youtube.com/playlist?list=PL64wiCrrxh4Jisi7OcCJIUpguV_f5jGnZ">Just for Func - Youtube</a></p>

<p><a href="https://www.goin5minutes.com/screencasts/">Go in 5 Minutes</a></p>

<p><a href="https://gophercises.com/">Gophercies</a></p>

<h2 id="concurrency">Concurrency</h2>

<p><a href="https://blog.golang.org/pipelines">Go Concurrency Patterns: Pipelines and Cancellation</a></p>

<p><a href="https://www.ardanlabs.com/blog/2017/10/the-behavior-of-channels.html">The Behavior of Channels - William Kennedy</a></p>

<p><a href="http://divan.github.io/posts/go_concurrency_visualize/">Visualizing Concurrency in Go</a></p>

<p><a href="https://www.ardanlabs.com/blog/2015/09/composition-with-go.html">Composition with Go - William Kennedy</a></p>

<h2 id="web-development">Web Development</h2>

<p><a href="https://www.gitbook.com/book/gobridge/building-web-apps-with-go/details">Building Web Apps with Go</a></p>

<p><a href="https://ewanvalentine.io/microservices-in-golang-part-1/">Microservices in Golang</a></p>

<h2 id="community">Community</h2>

<p><a href="https://forum.golangbridge.org/">Go Forum</a></p>

<p><a href="https://gophersinvite.herokuapp.com/">Gopher Slack</a> (#golang-newbies channel has a ton of great folks helping out, and it’s more of the general area for questions, not just newbies stuff)</p>]]></content><author><name></name></author><summary type="html"><![CDATA[I’ve been learning Go for a couple of months and have accumulated a ton of bookmarks and links on the subject. Recently I decided to prune through those and figure out which ones I found the most helpful when getting started. Below are some of my favorites that helped me in a wide variety of topics from completely getting started, to understanding some of the more complex topics specifically related to the most powerful features of Go.]]></summary></entry><entry><title type="html">Using NodeJS to Parse Daily Fantasy Sports (DFS) Lineups</title><link href="https://zacbaston.com/my-first-node-app/" rel="alternate" type="text/html" title="Using NodeJS to Parse Daily Fantasy Sports (DFS) Lineups" /><published>2016-11-17T00:00:00+00:00</published><updated>2016-11-17T00:00:00+00:00</updated><id>https://zacbaston.com/my-first-node-app</id><content type="html" xml:base="https://zacbaston.com/my-first-node-app/"><![CDATA[<p>Earlier this week a friend was talking about wanting to learn how to program and a project he wanted to complete. The basics of his idea are to get DFS lineups for contests, parse the data, calculate some frequency statistics and output that new information. Since I’m fairly new to developing applications and excited to learn more, I thought it would be fun to attempt this using NodeJS (a language I’ve never really used). While I’ve played and watched a lot of sports over my lifetime I’ve never played DFS, so please excuse my ignorance if I say something that is completely wrong.</p>

<p>To get started, I setup a new folder called <code class="language-plaintext highlighter-rouge">linup_frequency</code>, then moved into the directory and used <code class="language-plaintext highlighter-rouge">npm init</code> to create a <code class="language-plaintext highlighter-rouge">package.json</code> file with some basic metadata about the app.  When you do this, it asks what the entry point of your app is going to be and I just went with the default, <code class="language-plaintext highlighter-rouge">index.js</code>.  Next I type in <code class="language-plaintext highlighter-rouge">git init</code> to initialize my directory as a Git repository so I can track changes I make to the code.</p>

<p>Next I need to understand a little bit about what kind of data I’m going to be dealing with.  When a DFS contest is completed, a user can download a CSV file detailing various basic information about every lineup that was entered into the contest.  The CSV contains a header on the first line that looks similar to this:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Rank,EntryId,EntryName,TimeRemaining,Points,Lineup,,Player,%Drafted,FPTS
</code></pre></div></div>

<p>The key columns I’ll need to focus on are <code class="language-plaintext highlighter-rouge">Lineup</code> and <code class="language-plaintext highlighter-rouge">Player</code>.  I went ahead and studied the data a little bit looking through to see how these fields are structured so I could consider how to parse them later.</p>

<p>Knowing that I need to parse a CSV file using Node, I did what any sensible person would do and googled “node csv”.  After looking through a couple libraries, I decided on <a href="https://www.npmjs.com/package/fast-csv">fast-csv</a>.  This library has tons of downloads and solid documentation which was more than enough to get me off and running.  To download and install it, I just had to add a small bit of code to the <code class="language-plaintext highlighter-rouge">package.json</code> (as seen below), then run <code class="language-plaintext highlighter-rouge">npm install</code> from the command line.</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">{</span>
  <span class="p">...</span>
  <span class="dl">"</span><span class="s2">dependencies</span><span class="dl">"</span><span class="p">:</span> <span class="p">{</span>
		<span class="dl">"</span><span class="s2">fast-csv</span><span class="dl">"</span><span class="p">:</span> <span class="dl">"</span><span class="s2">~2.3.0</span><span class="dl">"</span>
	<span class="p">},</span>
  <span class="p">...</span>
<span class="p">}</span>
</code></pre></div></div>

<p>This command creates a new folder called <code class="language-plaintext highlighter-rouge">node_modules</code> and it’s the directory where Node libraries get installed locally, as in local to this project.  These modules can also be installed globally, but let’s not look into that just quite yet.  To make sure this installed correctly, we need to open up the <code class="language-plaintext highlighter-rouge">index.js</code> file and require the library like this:</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">var</span> <span class="nx">csv</span> <span class="o">=</span> <span class="nf">require</span><span class="p">(</span><span class="dl">'</span><span class="s1">fast-csv</span><span class="dl">'</span><span class="p">);</span>
<span class="nx">console</span><span class="p">.</span><span class="nf">log</span><span class="p">(</span><span class="dl">"</span><span class="s2">Hello World</span><span class="dl">"</span><span class="p">);</span>
</code></pre></div></div>
<p>Then run the application by typing <code class="language-plaintext highlighter-rouge">node index</code> into the command line.  If it there are no errors and you see “Hello World” in the console, things are working smoothly.</p>

<p>The CSV files that were provided for each contest were pretty large at over 100MB of text and commas, so I decided to copy one and truncate down to 10 rows of data while testing the program, which looks like this:</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nx">Rank</span><span class="p">,</span><span class="nx">EntryId</span><span class="p">,</span><span class="nx">EntryName</span><span class="p">,</span><span class="nx">TimeRemaining</span><span class="p">,</span><span class="nx">Points</span><span class="p">,</span><span class="nx">Lineup</span><span class="p">,,</span><span class="nx">Player</span><span class="p">,</span><span class="o">%</span><span class="nx">Drafted</span><span class="p">,</span><span class="nx">FPTS</span>
<span class="mi">1</span><span class="p">,</span><span class="mi">557031802</span><span class="p">,</span><span class="nx">ryanschumm</span><span class="p">,</span><span class="mi">0</span><span class="p">,</span><span class="mi">59</span><span class="p">,</span><span class="nx">C</span> <span class="nx">Nazem</span> <span class="nx">Kadri</span> <span class="nx">C</span> <span class="nx">Radek</span> <span class="nx">Faksa</span> <span class="nx">W</span> <span class="nx">Wayne</span> <span class="nx">Simmonds</span> <span class="nx">W</span> <span class="nx">Jordan</span> <span class="nx">Eberle</span> <span class="nx">W</span> <span class="nx">Mitchell</span> <span class="nx">Marner</span> <span class="nx">D</span> <span class="nx">Radko</span> <span class="nx">Gudas</span> <span class="nx">D</span> <span class="nx">Morgan</span> <span class="nx">Rielly</span> <span class="nx">G</span> <span class="nx">Keith</span> <span class="nx">Kinkaid</span> <span class="nx">UTIL</span> <span class="nx">Mark</span> <span class="nx">Scheifele</span><span class="p">,,</span><span class="nx">Connor</span> <span class="nx">McDavid</span><span class="p">,</span><span class="mf">27.15</span><span class="o">%</span><span class="p">,</span><span class="mi">4</span>
<span class="mi">2</span><span class="p">,</span><span class="mi">557767406</span><span class="p">,</span><span class="nf">suntzjim </span><span class="p">(</span><span class="mi">19</span><span class="o">/</span><span class="mi">22</span><span class="p">),</span><span class="mi">0</span><span class="p">,</span><span class="mf">58.4</span><span class="p">,</span><span class="nx">C</span> <span class="nx">Mikhail</span> <span class="nx">Grigorenko</span> <span class="nx">C</span> <span class="nx">Connor</span> <span class="nx">McDavid</span> <span class="nx">W</span> <span class="nx">Blake</span> <span class="nx">Wheeler</span> <span class="nx">W</span> <span class="nx">Wayne</span> <span class="nx">Simmonds</span> <span class="nx">W</span> <span class="nx">Patrick</span> <span class="nx">Maroon</span> <span class="nx">D</span> <span class="nx">Radko</span> <span class="nx">Gudas</span> <span class="nx">D</span> <span class="nx">Morgan</span> <span class="nx">Rielly</span> <span class="nx">G</span> <span class="nx">Craig</span> <span class="nx">Anderson</span> <span class="nx">UTIL</span> <span class="nx">Nikolaj</span> <span class="nx">Ehlers</span><span class="p">,,</span><span class="nx">Oscar</span> <span class="nx">Klefbom</span><span class="p">,</span><span class="mf">19.68</span><span class="o">%</span><span class="p">,</span><span class="mf">0.5</span>
<span class="mi">3</span><span class="p">,</span><span class="mi">557767409</span><span class="p">,</span><span class="nf">suntzjim </span><span class="p">(</span><span class="mi">22</span><span class="o">/</span><span class="mi">22</span><span class="p">),</span><span class="mi">0</span><span class="p">,</span><span class="mf">56.9</span><span class="p">,</span><span class="nx">C</span> <span class="nx">Sam</span> <span class="nx">Reinhart</span> <span class="nx">C</span> <span class="nx">Auston</span> <span class="nx">Matthews</span> <span class="nx">W</span> <span class="nx">Blake</span> <span class="nx">Wheeler</span> <span class="nx">W</span> <span class="nx">Wayne</span> <span class="nx">Simmonds</span> <span class="nx">W</span> <span class="nx">Patrick</span> <span class="nx">Maroon</span> <span class="nx">D</span> <span class="nx">Radko</span> <span class="nx">Gudas</span> <span class="nx">D</span> <span class="nx">Morgan</span> <span class="nx">Rielly</span> <span class="nx">G</span> <span class="nx">Braden</span> <span class="nx">Holtby</span> <span class="nx">UTIL</span> <span class="nx">Nikolaj</span> <span class="nx">Ehlers</span><span class="p">,,</span><span class="nx">Patrick</span> <span class="nx">Maroon</span><span class="p">,</span><span class="mf">19.38</span><span class="o">%</span><span class="p">,</span><span class="mf">5.5</span>
<span class="mi">4</span><span class="p">,</span><span class="mi">557349188</span><span class="p">,</span><span class="nx">Emanmae</span><span class="p">,</span><span class="mi">0</span><span class="p">,</span><span class="mf">56.7</span><span class="p">,</span><span class="nx">C</span> <span class="nx">Jeff</span> <span class="nx">Carter</span> <span class="nx">C</span> <span class="nx">Travis</span> <span class="nx">Zajac</span> <span class="nx">W</span> <span class="nx">Wayne</span> <span class="nx">Simmonds</span> <span class="nx">W</span> <span class="nx">Jordan</span> <span class="nx">Eberle</span> <span class="nx">W</span> <span class="nx">Marcus</span> <span class="nx">Johansson</span> <span class="nx">D</span> <span class="nx">Radko</span> <span class="nx">Gudas</span> <span class="nx">D</span> <span class="nx">Morgan</span> <span class="nx">Rielly</span> <span class="nx">G</span> <span class="nx">Anders</span> <span class="nx">Nilsson</span> <span class="nx">UTIL</span> <span class="nx">Blake</span> <span class="nx">Wheeler</span><span class="p">,,</span><span class="nx">Jordan</span> <span class="nx">Eberle</span><span class="p">,</span><span class="mf">18.58</span><span class="o">%</span><span class="p">,</span><span class="mi">4</span>
<span class="mi">5</span><span class="p">,</span><span class="mi">556972360</span><span class="p">,</span><span class="nc">Nufan55 </span><span class="p">(</span><span class="mi">2</span><span class="o">/</span><span class="mi">3</span><span class="p">),</span><span class="mi">0</span><span class="p">,</span><span class="mf">56.5</span><span class="p">,</span><span class="nx">C</span> <span class="nx">Tyler</span> <span class="nx">Bozak</span> <span class="nx">C</span> <span class="nx">Tyler</span> <span class="nx">Seguin</span> <span class="nx">W</span> <span class="nx">Patrick</span> <span class="nx">Eaves</span> <span class="nx">W</span> <span class="nx">Jamie</span> <span class="nx">Benn</span> <span class="nx">W</span> <span class="nx">Mitchell</span> <span class="nx">Marner</span> <span class="nx">D</span> <span class="nx">Radko</span> <span class="nx">Gudas</span> <span class="nx">D</span> <span class="nx">Morgan</span> <span class="nx">Rielly</span> <span class="nx">G</span> <span class="nx">Keith</span> <span class="nx">Kinkaid</span> <span class="nx">UTIL</span> <span class="nx">James</span> <span class="nx">van</span> <span class="nx">Riemsdyk</span><span class="p">,,</span><span class="nx">Keith</span> <span class="nx">Kinkaid</span><span class="p">,</span><span class="mf">17.60</span><span class="o">%</span><span class="p">,</span><span class="mi">7</span>
<span class="mi">6</span><span class="p">,</span><span class="mi">556996839</span><span class="p">,</span><span class="nf">awalker97 </span><span class="p">(</span><span class="mi">79</span><span class="o">/</span><span class="mi">150</span><span class="p">),</span><span class="mi">0</span><span class="p">,</span><span class="mf">56.4</span><span class="p">,</span><span class="nx">C</span> <span class="nx">Claude</span> <span class="nx">Giroux</span> <span class="nx">C</span> <span class="nx">Jean</span><span class="o">-</span><span class="nx">Gabriel</span> <span class="nx">Pageau</span> <span class="nx">W</span> <span class="nx">Wayne</span> <span class="nx">Simmonds</span> <span class="nx">W</span> <span class="nx">Zack</span> <span class="nx">Smith</span> <span class="nx">W</span> <span class="nx">Brayden</span> <span class="nx">Schenn</span> <span class="nx">D</span> <span class="nx">Erik</span> <span class="nx">Karlsson</span> <span class="nx">D</span> <span class="nx">Morgan</span> <span class="nx">Rielly</span> <span class="nx">G</span> <span class="nx">Craig</span> <span class="nx">Anderson</span> <span class="nx">UTIL</span> <span class="nx">Ryan</span> <span class="nx">Dzingel</span><span class="p">,,</span><span class="nx">Claude</span> <span class="nx">Giroux</span><span class="p">,</span><span class="mf">17.41</span><span class="o">%</span><span class="p">,</span><span class="mf">3.5</span>
<span class="mi">7</span><span class="p">,</span><span class="mi">556961451</span><span class="p">,</span><span class="nf">theedeazz </span><span class="p">(</span><span class="mi">5</span><span class="o">/</span><span class="mi">8</span><span class="p">),</span><span class="mi">0</span><span class="p">,</span><span class="mf">56.2</span><span class="p">,</span><span class="nx">C</span> <span class="nx">Claude</span> <span class="nx">Giroux</span> <span class="nx">C</span> <span class="nx">Tyler</span> <span class="nx">Seguin</span> <span class="nx">W</span> <span class="nx">Wayne</span> <span class="nx">Simmonds</span> <span class="nx">W</span> <span class="nx">Tyler</span> <span class="nx">Pitlick</span> <span class="nx">W</span> <span class="nx">Antoine</span> <span class="nx">Roussel</span> <span class="nx">D</span> <span class="nx">Morgan</span> <span class="nx">Rielly</span> <span class="nx">D</span> <span class="nx">Shayne</span> <span class="nx">Gostisbehere</span> <span class="nx">G</span> <span class="nx">Anders</span> <span class="nx">Nilsson</span> <span class="nx">UTIL</span> <span class="nx">Patrick</span> <span class="nx">Eaves</span><span class="p">,,</span><span class="nx">Patrik</span> <span class="nx">Laine</span><span class="p">,</span><span class="mf">15.87</span><span class="o">%</span><span class="p">,</span><span class="mi">1</span>
<span class="mi">8</span><span class="p">,</span><span class="mi">556796292</span><span class="p">,</span><span class="nc">Thorty </span><span class="p">(</span><span class="mi">108</span><span class="o">/</span><span class="mi">150</span><span class="p">),</span><span class="mi">0</span><span class="p">,</span><span class="mf">55.5</span><span class="p">,</span><span class="nx">C</span> <span class="nx">Nazem</span> <span class="nx">Kadri</span> <span class="nx">C</span> <span class="nx">Tyler</span> <span class="nx">Seguin</span> <span class="nx">W</span> <span class="nx">Patrick</span> <span class="nx">Eaves</span> <span class="nx">W</span> <span class="nx">Antoine</span> <span class="nx">Roussel</span> <span class="nx">W</span> <span class="nx">Leo</span> <span class="nx">Komarov</span> <span class="nx">D</span> <span class="nx">Erik</span> <span class="nx">Karlsson</span> <span class="nx">D</span> <span class="nx">Morgan</span> <span class="nx">Rielly</span> <span class="nx">G</span> <span class="nx">Frederik</span> <span class="nx">Andersen</span> <span class="nx">UTIL</span> <span class="nx">Connor</span> <span class="nx">Brown</span><span class="p">,,</span><span class="nx">Nikolaj</span> <span class="nx">Ehlers</span><span class="p">,</span><span class="mf">15.83</span><span class="o">%</span><span class="p">,</span><span class="mf">4.5</span>
<span class="mi">9</span><span class="p">,</span><span class="mi">556796271</span><span class="p">,</span><span class="nc">Thorty </span><span class="p">(</span><span class="mi">87</span><span class="o">/</span><span class="mi">150</span><span class="p">),</span><span class="mi">0</span><span class="p">,</span><span class="mi">55</span><span class="p">,</span><span class="nx">C</span> <span class="nx">Tyler</span> <span class="nx">Bozak</span> <span class="nx">C</span> <span class="nx">Tyler</span> <span class="nx">Seguin</span> <span class="nx">W</span> <span class="nx">James</span> <span class="nx">van</span> <span class="nx">Riemsdyk</span> <span class="nx">W</span> <span class="nx">Antoine</span> <span class="nx">Roussel</span> <span class="nx">W</span> <span class="nx">Mitchell</span> <span class="nx">Marner</span> <span class="nx">D</span> <span class="nx">Erik</span> <span class="nx">Karlsson</span> <span class="nx">D</span> <span class="nx">Morgan</span> <span class="nx">Rielly</span> <span class="nx">G</span> <span class="nx">Frederik</span> <span class="nx">Andersen</span> <span class="nx">UTIL</span> <span class="nx">Patrick</span> <span class="nx">Eaves</span><span class="p">,,</span><span class="nx">Jakub</span> <span class="nx">Voracek</span><span class="p">,</span><span class="mf">15.51</span><span class="o">%</span><span class="p">,</span><span class="mi">0</span>
<span class="mi">9</span><span class="p">,</span><span class="mi">556963453</span><span class="p">,</span><span class="nf">fewfew </span><span class="p">(</span><span class="mi">93</span><span class="o">/</span><span class="mi">150</span><span class="p">),</span><span class="mi">0</span><span class="p">,</span><span class="mi">55</span><span class="p">,</span><span class="nx">C</span> <span class="nx">Tyler</span> <span class="nx">Bozak</span> <span class="nx">C</span> <span class="nx">Tyler</span> <span class="nx">Seguin</span> <span class="nx">W</span> <span class="nx">James</span> <span class="nx">van</span> <span class="nx">Riemsdyk</span> <span class="nx">W</span> <span class="nx">Antoine</span> <span class="nx">Roussel</span> <span class="nx">W</span> <span class="nx">Mitchell</span> <span class="nx">Marner</span> <span class="nx">D</span> <span class="nx">Erik</span> <span class="nx">Karlsson</span> <span class="nx">D</span> <span class="nx">Morgan</span> <span class="nx">Rielly</span> <span class="nx">G</span> <span class="nx">Frederik</span> <span class="nx">Andersen</span> <span class="nx">UTIL</span> <span class="nx">Patrick</span> <span class="nx">Eaves</span><span class="p">,,</span><span class="nx">James</span> <span class="nx">van</span> <span class="nx">Riemsdyk</span><span class="p">,</span><span class="mf">15.33</span><span class="o">%</span><span class="p">,</span><span class="mi">3</span>
<span class="mi">11</span><span class="p">,</span><span class="mi">557767395</span><span class="p">,</span><span class="nf">suntzjim </span><span class="p">(</span><span class="mi">8</span><span class="o">/</span><span class="mi">22</span><span class="p">),</span><span class="mi">0</span><span class="p">,</span><span class="mf">54.9</span><span class="p">,</span><span class="nx">C</span> <span class="nx">Matt</span> <span class="nx">Duchene</span> <span class="nx">C</span> <span class="nx">Nazem</span> <span class="nx">Kadri</span> <span class="nx">W</span> <span class="nx">Blake</span> <span class="nx">Wheeler</span> <span class="nx">W</span> <span class="nx">Wayne</span> <span class="nx">Simmonds</span> <span class="nx">W</span> <span class="nx">Patrick</span> <span class="nx">Maroon</span> <span class="nx">D</span> <span class="nx">Oscar</span> <span class="nx">Klefbom</span> <span class="nx">D</span> <span class="nx">Morgan</span> <span class="nx">Rielly</span> <span class="nx">G</span> <span class="nx">Craig</span> <span class="nx">Anderson</span> <span class="nx">UTIL</span> <span class="nx">Nikolaj</span> <span class="nx">Ehlers</span><span class="p">,,</span><span class="nx">Anders</span> <span class="nx">Nilsson</span><span class="p">,</span><span class="mf">15.17</span><span class="o">%</span><span class="p">,</span><span class="mf">6.2</span>
</code></pre></div></div>

<p>Now With the library loading properly and some test data, it’s time to how to use fast-csv to actually parse the file.  fast-csv has <a href="https://www.npmjs.com/package/fast-csv">solid documentation</a> which shows a variety of ways to read through files.  After looking through all the options, I decided to use the <code class="language-plaintext highlighter-rouge">.fromStream</code> option which accepts a read stream created by <a href="https://nodejs.org/api/fs.html">Node’s File System library</a> referenced by <code class="language-plaintext highlighter-rouge">fs</code> in the code and an options object which allows us to customize how the CSV is read.  For example, we’re passing in the <code class="language-plaintext highlighter-rouge">{ headers: true }</code> parameter to indicate the first line of the file includes the column names.  Then in the example code there there are several event listeners which are the bits of code that start with <code class="language-plaintext highlighter-rouge">.on(event)</code>.  The first event we see is “data” which turns out being each row in context of a CSV file.  Inside that event listener, I’m simply logging the row as it appears so I can see what it looks like at that moment in the program.  So this will log each row to the console, then once complete it will hit the next event listener “end”, which then logs the string “done” to indicate the program is done parsing.</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">var</span> <span class="nx">csv</span> <span class="o">=</span> <span class="nf">require</span><span class="p">(</span><span class="dl">'</span><span class="s1">fast-csv</span><span class="dl">'</span><span class="p">),</span>
     <span class="nx">fs</span> <span class="o">=</span> <span class="nf">require</span><span class="p">(</span><span class="dl">'</span><span class="s1">fs</span><span class="dl">'</span><span class="p">);</span>

<span class="kd">var</span> <span class="nx">stream</span> <span class="o">=</span> <span class="nx">fs</span><span class="p">.</span><span class="nf">createReadStream</span><span class="p">(</span><span class="dl">"</span><span class="s2">contest-truncate.csv</span><span class="dl">"</span><span class="p">);</span>

<span class="nx">csv</span>
 <span class="p">.</span><span class="nf">fromStream</span><span class="p">(</span><span class="nx">stream</span><span class="p">,</span> <span class="p">{</span><span class="na">headers</span> <span class="p">:</span> <span class="kc">true</span><span class="p">})</span>
 <span class="p">.</span><span class="nf">on</span><span class="p">(</span><span class="dl">"</span><span class="s2">data</span><span class="dl">"</span><span class="p">,</span> <span class="kd">function</span><span class="p">(</span><span class="nx">row</span><span class="p">){</span>
     <span class="nx">console</span><span class="p">.</span><span class="nf">log</span><span class="p">(</span><span class="nx">row</span><span class="p">);</span>
 <span class="p">})</span>
 <span class="p">.</span><span class="nf">on</span><span class="p">(</span><span class="dl">"</span><span class="s2">end</span><span class="dl">"</span><span class="p">,</span> <span class="kd">function</span><span class="p">(){</span>
     <span class="nx">console</span><span class="p">.</span><span class="nf">log</span><span class="p">(</span><span class="dl">"</span><span class="s2">done</span><span class="dl">"</span><span class="p">);</span>
<span class="p">});</span>
</code></pre></div></div>

<p>When we run this using <code class="language-plaintext highlighter-rouge">node index</code>, the console then races by with a wall of text and each row looks like it gets converted to an object like this:</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code> <span class="p">{</span> <span class="nl">Rank</span><span class="p">:</span> <span class="dl">'</span><span class="s1">1</span><span class="dl">'</span><span class="p">,</span>
   <span class="nx">EntryId</span><span class="p">:</span> <span class="dl">'</span><span class="s1">557031802</span><span class="dl">'</span><span class="p">,</span>
   <span class="nx">EntryName</span><span class="p">:</span> <span class="dl">'</span><span class="s1">ryanschumm</span><span class="dl">'</span><span class="p">,</span>
   <span class="nx">TimeRemaining</span><span class="p">:</span> <span class="dl">'</span><span class="s1">0</span><span class="dl">'</span><span class="p">,</span>
   <span class="nx">Points</span><span class="p">:</span> <span class="dl">'</span><span class="s1">59</span><span class="dl">'</span><span class="p">,</span>
   <span class="nx">Lineup</span><span class="p">:</span> <span class="dl">'</span><span class="s1">C Nazem Kadri C Radek Faksa W Wayne Simmonds W Jordan Eberle W Mitchell Marner D Radko Gudas D Morgan Rielly G Keith Kinkaid UTIL Mark Scheifele</span><span class="dl">'</span><span class="p">,</span>
   <span class="dl">''</span><span class="p">:</span> <span class="dl">''</span><span class="p">,</span>
   <span class="nx">Player</span><span class="p">:</span> <span class="dl">'</span><span class="s1">Connor McDavid</span><span class="dl">'</span><span class="p">,</span>
   <span class="dl">'</span><span class="s1">%Drafted</span><span class="dl">'</span><span class="p">:</span> <span class="dl">'</span><span class="s1">27.15%</span><span class="dl">'</span><span class="p">,</span>
   <span class="nx">FPTS</span><span class="p">:</span> <span class="dl">'</span><span class="s1">4</span><span class="dl">'</span> <span class="p">}</span>
</code></pre></div></div>

<p>This is great information since it shows me how to access each column of the row while inside the callback function for the “data” event listener.  Now I need to figure a couple of things out, 1) how do I extract the individual names from the <code class="language-plaintext highlighter-rouge">Lineup</code> attribute and 2) how am I going to store that information within the program.  For the first problem, I’m writing a method called <code class="language-plaintext highlighter-rouge">getPlayersFromLineup()</code> which takes in two arguments from each row, <code class="language-plaintext highlighter-rouge">row.Lineup</code> and <code class="language-plaintext highlighter-rouge">row.Player</code>. To extract the values from the lineup, I decided to use a regular expression.  Below is the code I used for this function.  First it saves the regex to a local variable, then it uses the <code class="language-plaintext highlighter-rouge">.split</code> method on the <code class="language-plaintext highlighter-rouge">lineup</code> to extract each player name.  Next this leaves an empty string at the beginning of the <code class="language-plaintext highlighter-rouge">splitLineup</code> array, so we use the <code class="language-plaintext highlighter-rouge">splice</code> method to remove that and then add the other <code class="language-plaintext highlighter-rouge">player</code> argument to this <code class="language-plaintext highlighter-rouge">newLineup</code> array.  Finally we return this <code class="language-plaintext highlighter-rouge">newLineup</code> array which is just a list of player names.</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">function</span> <span class="nf">getPlayersFromLineup</span><span class="p">(</span><span class="nx">lineup</span><span class="p">,</span> <span class="nx">player</span><span class="p">)</span> <span class="p">{</span>
    <span class="kd">var</span> <span class="nx">regex</span> <span class="o">=</span> <span class="sr">/C</span><span class="se">\W</span><span class="sr">|W</span><span class="se">\W</span><span class="sr">|D</span><span class="se">\W</span><span class="sr">|G</span><span class="se">\W</span><span class="sr">|UTIL</span><span class="se">\W</span><span class="sr">/g</span><span class="p">;</span>
    <span class="kd">var</span> <span class="nx">splitLineup</span> <span class="o">=</span> <span class="nx">lineup</span><span class="p">.</span><span class="nf">split</span><span class="p">(</span><span class="nx">regex</span><span class="p">);</span>
    <span class="kd">var</span> <span class="nx">newLineup</span> <span class="o">=</span> <span class="nx">splitLineup</span><span class="p">.</span><span class="nf">slice</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span><span class="nx">splitLineup</span><span class="p">.</span><span class="nx">length</span><span class="p">);</span>
    <span class="nx">newLineup</span><span class="p">.</span><span class="nf">push</span><span class="p">(</span><span class="nx">player</span><span class="p">);</span>
    <span class="k">return</span> <span class="nx">newLineup</span>
<span class="p">}</span>
</code></pre></div></div>

<p>For the second problem, my choice for storing all the players is an object since they are very fast and it is relatively easy to store each player as a key-value pair with the player’s name being the key and the value being incremented each time they are recognized in a lineup.  To do this, I need to implement two new methods, one called <code class="language-plaintext highlighter-rouge">processLineup()</code> and another called <code class="language-plaintext highlighter-rouge">addPlayerToPlayers()</code>.  The <code class="language-plaintext highlighter-rouge">processLineup</code> function takes in a full lineup of players, which is an array.  The first step in this method modifies each entry in the <code class="language-plaintext highlighter-rouge">lineup</code> array by trimming off any empty space at the end of each string.  Next it uses a <code class="language-plaintext highlighter-rouge">.forEach</code> iterator to first check and make sure each item isn’t an empty string.  Then it passes the <code class="language-plaintext highlighter-rouge">player</code> name to the <code class="language-plaintext highlighter-rouge">addPlayerToPlayers</code> function.  This function simply checks to see if there is already an entry in the <code class="language-plaintext highlighter-rouge">players</code> object with a key that shares the players name.  If this entry exists, then it simply increments that value by one.  If there is no entry, then it puts the player into the players object and sets it’s value to 1.</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">var</span> <span class="nx">players</span> <span class="o">=</span> <span class="p">{};</span>

<span class="kd">function</span> <span class="nf">processLineup</span><span class="p">(</span><span class="nx">lineup</span><span class="p">){</span>
    <span class="kd">var</span> <span class="nx">processedLineup</span> <span class="o">=</span> <span class="nx">lineup</span><span class="p">.</span><span class="nf">map</span><span class="p">(</span><span class="nb">Function</span><span class="p">.</span><span class="nx">prototype</span><span class="p">.</span><span class="nx">call</span><span class="p">,</span> <span class="nb">String</span><span class="p">.</span><span class="nx">prototype</span><span class="p">.</span><span class="nx">trim</span><span class="p">);</span>

    <span class="nx">processedLineup</span><span class="p">.</span><span class="nf">forEach</span><span class="p">(</span><span class="kd">function</span><span class="p">(</span><span class="nx">player</span><span class="p">){</span>
        <span class="k">if </span><span class="p">(</span><span class="nx">player</span><span class="p">)</span> <span class="p">{</span>
            <span class="nf">addPlayerToPlayers</span><span class="p">(</span><span class="nx">player</span><span class="p">);</span>
        <span class="p">}</span>
    <span class="p">});</span>
<span class="p">}</span>

<span class="kd">function</span> <span class="nf">addPlayerToPlayers</span><span class="p">(</span><span class="nx">player</span><span class="p">)</span> <span class="p">{</span>
    <span class="k">if </span><span class="p">(</span><span class="nx">players</span><span class="p">[</span><span class="nx">player</span><span class="p">])</span> <span class="p">{</span>
        <span class="nx">players</span><span class="p">[</span><span class="nx">player</span><span class="p">]</span> <span class="o">++</span><span class="p">;</span>
    <span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
        <span class="nx">players</span><span class="p">[</span><span class="nx">player</span><span class="p">]</span> <span class="o">=</span> <span class="mi">1</span><span class="p">;</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>The main part of the script looks like this:</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nx">csv</span>
    <span class="p">.</span><span class="nf">fromStream</span><span class="p">(</span><span class="nx">readStream</span><span class="p">,</span> <span class="p">{</span> <span class="na">headers</span><span class="p">:</span> <span class="kc">true</span><span class="p">})</span>
    <span class="p">.</span><span class="nf">on</span><span class="p">(</span><span class="dl">"</span><span class="s2">data</span><span class="dl">"</span><span class="p">,</span> <span class="kd">function</span><span class="p">(</span><span class="nx">row</span><span class="p">){</span>
        <span class="kd">var</span> <span class="nx">rowLineup</span> <span class="o">=</span> <span class="nf">getPlayersFromLineup</span><span class="p">(</span><span class="nx">row</span><span class="p">.</span><span class="nx">Lineup</span><span class="p">,</span> <span class="nx">row</span><span class="p">.</span><span class="nx">Player</span><span class="p">);</span>
        <span class="nf">processLineup</span><span class="p">(</span><span class="nx">rowLineup</span><span class="p">);</span>
    <span class="p">})</span>
    <span class="p">.</span><span class="nf">on</span><span class="p">(</span><span class="dl">"</span><span class="s2">end</span><span class="dl">"</span><span class="p">,</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
        <span class="nx">console</span><span class="p">.</span><span class="nf">log</span><span class="p">(</span><span class="dl">"</span><span class="s2">Done</span><span class="dl">"</span><span class="p">)</span>
    <span class="p">})</span>
</code></pre></div></div>

<p>And all of the players are stored in the <code class="language-plaintext highlighter-rouge">players</code> object.  So now we need to figure out how to print out this object in a nice and readable format.  To do this I will implement a method called <code class="language-plaintext highlighter-rouge">printOutput()</code> which takes in the <code class="language-plaintext highlighter-rouge">players</code> object.  This function utilizes a variable called <code class="language-plaintext highlighter-rouge">counter</code> so I can track the rank of each player.  Then it iterates through all of the players and logs their <code class="language-plaintext highlighter-rouge">counter</code>, name, and value.</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">function</span> <span class="nf">printOutput</span><span class="p">(</span><span class="nx">players</span><span class="p">)</span> <span class="p">{</span>
    <span class="kd">var</span> <span class="nx">counter</span> <span class="o">=</span> <span class="mi">1</span><span class="p">;</span>
    <span class="nx">players</span><span class="p">.</span><span class="nf">forEach</span><span class="p">(</span><span class="kd">function</span><span class="p">(</span><span class="nx">player</span><span class="p">)</span> <span class="p">{</span>
        <span class="nx">console</span><span class="p">.</span><span class="nf">log</span><span class="p">(</span><span class="s2">`</span><span class="p">${</span><span class="nx">counter</span><span class="p">}</span><span class="s2">. </span><span class="p">${</span><span class="nx">player</span><span class="p">[</span><span class="mi">0</span><span class="p">]}</span><span class="s2">, </span><span class="p">${</span><span class="nx">player</span><span class="p">[</span><span class="mi">1</span><span class="p">]}</span><span class="s2">`</span><span class="p">)</span>
        <span class="nx">counter</span><span class="o">++</span><span class="p">;</span>
    <span class="p">});</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Great!  We’re now printing out some data, but unfortunately it is sorted in a random order.  So at this point I googled how to sort a javascript object by the values and I found <a href="http://stackoverflow.com/questions/1069666/sorting-javascript-object-by-property-value">the function below on StackOverflow</a>.</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">function</span> <span class="nf">sortProperties</span><span class="p">(</span><span class="nx">obj</span><span class="p">)</span> <span class="p">{</span>
    <span class="kd">var</span> <span class="nx">sortable</span><span class="o">=</span><span class="p">[];</span>
    <span class="k">for</span><span class="p">(</span><span class="kd">var</span> <span class="nx">key</span> <span class="k">in</span> <span class="nx">obj</span><span class="p">)</span>
        <span class="k">if</span><span class="p">(</span><span class="nx">obj</span><span class="p">.</span><span class="nf">hasOwnProperty</span><span class="p">(</span><span class="nx">key</span><span class="p">))</span>
            <span class="nx">sortable</span><span class="p">.</span><span class="nf">push</span><span class="p">([</span><span class="nx">key</span><span class="p">,</span> <span class="nx">obj</span><span class="p">[</span><span class="nx">key</span><span class="p">]]);</span>

    <span class="nx">sortable</span><span class="p">.</span><span class="nf">sort</span><span class="p">(</span><span class="kd">function</span><span class="p">(</span><span class="nx">a</span><span class="p">,</span> <span class="nx">b</span><span class="p">)</span> <span class="p">{</span>
      <span class="k">return</span> <span class="nx">a</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span><span class="o">-</span><span class="nx">b</span><span class="p">[</span><span class="mi">1</span><span class="p">];</span>
    <span class="p">});</span>

    <span class="k">return</span> <span class="nx">sortable</span><span class="p">.</span><span class="nf">reverse</span><span class="p">();</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Finally our program is able to parse, sort, and print out some useable information!  At this point, the program will only print out the total number of times a player’s name occurs in the CSV file, but what we really want is that number divided by the total number of lineups that were entered.  To do this I simply need to create another counter variable before I parse the CSV.  I’ll call it <code class="language-plaintext highlighter-rouge">index</code>, and then for each row that is parsed, I need to increment this variable.  Then in the <code class="language-plaintext highlighter-rouge">printOutput()</code> function, I need to divide the <code class="language-plaintext highlighter-rouge">player[1]</code> by this index variable to produce a decimal percentage.  The core of our CSV parser now looks like this:</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nx">csv</span>
    <span class="p">.</span><span class="nf">fromStream</span><span class="p">(</span><span class="nx">readStream</span><span class="p">,</span> <span class="p">{</span> <span class="na">headers</span><span class="p">:</span> <span class="kc">true</span><span class="p">})</span>
    <span class="p">.</span><span class="nf">on</span><span class="p">(</span><span class="dl">"</span><span class="s2">data</span><span class="dl">"</span><span class="p">,</span> <span class="kd">function</span><span class="p">(</span><span class="nx">row</span><span class="p">){</span>
        <span class="kd">var</span> <span class="nx">rowLineup</span> <span class="o">=</span> <span class="nf">getPlayersFromLineup</span><span class="p">(</span><span class="nx">row</span><span class="p">.</span><span class="nx">Lineup</span><span class="p">,</span> <span class="nx">row</span><span class="p">.</span><span class="nx">Player</span><span class="p">);</span>
        <span class="nf">processLineup</span><span class="p">(</span><span class="nx">rowLineup</span><span class="p">);</span>
        <span class="nx">index</span> <span class="o">++</span><span class="p">;</span>
    <span class="p">})</span>
    <span class="p">.</span><span class="nf">on</span><span class="p">(</span><span class="dl">"</span><span class="s2">end</span><span class="dl">"</span><span class="p">,</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
        <span class="kd">var</span> <span class="nx">sortedPlayers</span> <span class="o">=</span> <span class="nf">sortProperties</span><span class="p">(</span><span class="nx">players</span><span class="p">);</span>
        <span class="nf">printOutput</span><span class="p">(</span><span class="nx">sortedPlayers</span><span class="p">);</span>
    <span class="p">})</span>
</code></pre></div></div>

<p>The program is now printing out the ranking and frequency each player occurs in the lineups.  So I have accomplished my goal.  YAY! All this code is posted up on Github: <a href="https://github.com/zacscodingclub/lineup-frequency/blob/master/index.js">Lineup frequency</a>.  In that code I have implemented a few more features to make the program more flexible, so it will look a little bit different but the functionality explained in this post is still the heart of the program.</p>]]></content><author><name></name></author><summary type="html"><![CDATA[Earlier this week a friend was talking about wanting to learn how to program and a project he wanted to complete. The basics of his idea are to get DFS lineups for contests, parse the data, calculate some frequency statistics and output that new information. Since I’m fairly new to developing applications and excited to learn more, I thought it would be fun to attempt this using NodeJS (a language I’ve never really used). While I’ve played and watched a lot of sports over my lifetime I’ve never played DFS, so please excuse my ignorance if I say something that is completely wrong.]]></summary></entry><entry><title type="html">Building an Angular Application on a Rails Backend: Part 3</title><link href="https://zacbaston.com/rails-angular-app-part-3/" rel="alternate" type="text/html" title="Building an Angular Application on a Rails Backend: Part 3" /><published>2016-10-01T00:00:00+00:00</published><updated>2016-10-01T00:00:00+00:00</updated><id>https://zacbaston.com/rails-angular-app-part-3</id><content type="html" xml:base="https://zacbaston.com/rails-angular-app-part-3/"><![CDATA[<p>This is the third of a three part series about the insights I gained while building my first AngularJS application using Ruby on Rails in the back-end. This particular post is about setting up the front-end templates and interacting with the Rails back end using Angular factories. There are almost certainly better ways to do some of these things, but this is how I did it and what I learned.</p>

<hr />

<p>After the last <a href="http://zacscodingclub.github.io/rails-angular-app-part-2/">blog post</a>, I have a basic Rails application back end with a basic Angular controller in place.  At this point, the only data that exists within this controller is just a simple string variable put in place to test that there aren’t any errors with the setup.</p>

<p>The first step to complete is to include the modules we need in <code class="language-plaintext highlighter-rouge">app.js</code>.  This can be accomplished in a couple steps.  First, since we’re using Rails, one of the needed modules can be packed into the application by adding <code class="language-plaintext highlighter-rouge">gem 'angular-rails-templates'</code> to the Gemfile and running <code class="language-plaintext highlighter-rouge">bundle install</code>. For the other two needed modules, I need to download the actual source code and save that into the <code class="language-plaintext highlighter-rouge">app/assets/javascripts</code> directory.  The modules I need to obtain are <a href="https://github.com/angular-ui/ui-router">ui.router</a> and <a href="https://docs.angularjs.org/api/ngMessages/directive/ngMessages">ngMessages</a>.  As with any javascript files in Rails, I need to add all of those modules to the <a href="http://guides.rubyonrails.org/asset_pipeline.html">Asset Pipeline</a> as well by making sure to add the following lines to the <code class="language-plaintext highlighter-rouge">application.js</code> file:</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">//= require angular-ui-router</span>
<span class="c1">//= require angular-resource</span>
<span class="c1">//= require angular-rails-templates</span>
</code></pre></div></div>

<p>Finally I can add each module to the initialization of the angular app in <code class="language-plaintext highlighter-rouge">app.js</code> using the second bit of code below:</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code>  <span class="c1">// Previous code</span>
  <span class="nx">angular</span>
    <span class="p">.</span><span class="nf">module</span><span class="p">(</span><span class="dl">'</span><span class="s1">trackazon</span><span class="dl">'</span><span class="p">,</span> <span class="p">[]);</span>

  <span class="c1">// New code with modules added</span>
  <span class="nx">angular</span>
    <span class="p">.</span><span class="nf">module</span><span class="p">(</span><span class="dl">'</span><span class="s1">trackazon</span><span class="dl">'</span><span class="p">,</span> <span class="p">[</span><span class="dl">'</span><span class="s1">ui.router</span><span class="dl">'</span><span class="p">,</span> <span class="dl">'</span><span class="s1">templates</span><span class="dl">'</span><span class="p">,</span> <span class="dl">'</span><span class="s1">ngMessages</span><span class="dl">'</span><span class="p">])</span>
</code></pre></div></div>
<p>It’s simple to determine if any errors have been made by starting up the server using <code class="language-plaintext highlighter-rouge">rails s</code>, load the page in a browser, then check the browser’s console.</p>

<p>With no errors, I need to create a route and wire it up to a template and controller.</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code>  <span class="nx">angular</span>
    <span class="p">.</span><span class="nf">module</span><span class="p">(</span><span class="dl">'</span><span class="s1">app</span><span class="dl">'</span><span class="p">,</span> <span class="p">[</span><span class="dl">'</span><span class="s1">ui.router</span><span class="dl">'</span><span class="p">,</span> <span class="dl">'</span><span class="s1">templates</span><span class="dl">'</span><span class="p">,</span> <span class="dl">'</span><span class="s1">ngMessages</span><span class="dl">'</span><span class="p">])</span>
    <span class="p">.</span><span class="nf">config</span><span class="p">(</span><span class="kd">function</span><span class="p">(</span><span class="nx">$stateProvider</span><span class="p">,</span> <span class="nx">$urlRouterProvider</span><span class="p">)</span> <span class="p">{</span>
      <span class="nx">$stateProvider</span>
        <span class="p">.</span><span class="nf">state</span><span class="p">(</span><span class="dl">'</span><span class="s1">inventory</span><span class="dl">'</span><span class="p">,</span> <span class="p">{</span>
          <span class="na">url</span><span class="p">:</span> <span class="dl">'</span><span class="s1">/</span><span class="dl">'</span><span class="p">,</span>
          <span class="na">templateUrl</span><span class="p">:</span> <span class="dl">'</span><span class="s1">products/index.html</span><span class="dl">'</span><span class="p">,</span>
          <span class="na">controller</span><span class="p">:</span> <span class="dl">'</span><span class="s1">InventoryController as vm</span><span class="dl">'</span>
        <span class="p">})</span>

    <span class="nx">$urlRouterProvider</span><span class="p">.</span><span class="nf">otherwise</span><span class="p">(</span><span class="dl">'</span><span class="s1">/</span><span class="dl">'</span><span class="p">);</span>
    <span class="p">});</span>
</code></pre></div></div>
<p>Here we have drawn a route called <code class="language-plaintext highlighter-rouge">inventory</code> which is mapped to the url ‘/’.  Since Angular will add a hashtag (#) to the end of the URL, this inventory route having a url of ‘/’ means that the URL in the browser will end with <code class="language-plaintext highlighter-rouge">#/</code>.  This route also has defined a template called ‘products/index.html’, which means I need to create a directory within <code class="language-plaintext highlighter-rouge">app/assets/javascripts/</code> called ‘products’ and an ‘index.html’ file inside that new directory.</p>

<p>Also, since I set the controller for this route to ‘InventoryController’, I need to build a controller action which will kick off a process to access the products in the database.  We already have this controller from the previous sections, but some stuff needs to be updated.</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nx">angular</span>
  <span class="p">.</span><span class="nf">module</span><span class="p">(</span><span class="dl">'</span><span class="s1">trackazon</span><span class="dl">'</span><span class="p">)</span>
  <span class="p">.</span><span class="nf">controller</span><span class="p">(</span><span class="dl">'</span><span class="s1">InventoryController</span><span class="dl">'</span><span class="p">,</span> <span class="kd">function</span><span class="p">(</span><span class="nx">$scope</span><span class="p">)</span> <span class="p">{</span>
    <span class="kd">var</span> <span class="nx">ctrl</span> <span class="o">=</span> <span class="k">this</span><span class="p">;</span>

    <span class="nx">ctrl</span><span class="p">.</span><span class="nx">products</span> <span class="o">=</span> <span class="p">[];</span>

    <span class="nx">ctrl</span><span class="p">.</span><span class="nx">getProducts</span> <span class="o">=</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
      <span class="nx">ProductService</span><span class="p">.</span><span class="nf">getProducts</span><span class="p">()</span>
          <span class="p">.</span><span class="nf">then</span><span class="p">(</span><span class="kd">function</span><span class="p">(</span><span class="nx">response</span><span class="p">)</span> <span class="p">{</span>
            <span class="nx">ctrl</span><span class="p">.</span><span class="nx">products</span> <span class="o">=</span> <span class="nx">response</span><span class="p">.</span><span class="nx">data</span><span class="p">;</span>
          <span class="p">},</span> <span class="kd">function</span><span class="p">(</span><span class="nx">error</span><span class="p">)</span> <span class="p">{</span>
            <span class="nx">console</span><span class="p">.</span><span class="nf">log</span><span class="p">(</span><span class="dl">"</span><span class="s2">Error occurred: </span><span class="dl">"</span> <span class="o">+</span> <span class="nx">error</span><span class="p">);</span>
          <span class="p">})</span>
      <span class="p">}</span>
    <span class="p">});</span>
</code></pre></div></div>
<p>Alright, so what just happened there is I set a variable <code class="language-plaintext highlighter-rouge">ctrl</code> equal to the InventoryController so it’s easier to understand what scope I’m in later in the controller.  Next I set a controller variable <code class="language-plaintext highlighter-rouge">products</code> equal to an empty array so I can have a structure to hold data in later.  Lastly I make a function whose job is to go out and get the products data from the database.  But wait, you may notice that I used something called <code class="language-plaintext highlighter-rouge">ProductService</code>, which I haven’t explained yet.</p>

<p>A service in Angular is a great way to extract interaction with a database or external source into it’s own home.  In this case, the <code class="language-plaintext highlighter-rouge">ProductService</code> will simply interact with the local database we created using Rails.  Creating a service is fairly straightforward as you can see in the code below:</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code>  <span class="nx">angular</span>
    <span class="p">.</span><span class="nf">module</span><span class="p">(</span><span class="dl">'</span><span class="s1">trackazon</span><span class="dl">'</span><span class="p">)</span>
    <span class="p">.</span><span class="nf">service</span><span class="p">(</span><span class="dl">'</span><span class="s1">ProductService</span><span class="dl">'</span><span class="p">,[</span><span class="dl">'</span><span class="s1">$http</span><span class="dl">'</span><span class="p">,</span> <span class="kd">function</span><span class="p">(</span><span class="nx">$http</span><span class="p">)</span> <span class="p">{</span>
      <span class="k">this</span><span class="p">.</span><span class="nx">getProducts</span> <span class="o">=</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
        <span class="k">return</span> <span class="nx">$http</span><span class="p">.</span><span class="nf">get</span><span class="p">(</span><span class="dl">'</span><span class="s1">/products.json</span><span class="dl">'</span><span class="p">);</span>
      <span class="p">}</span>
    <span class="p">}]);</span>
</code></pre></div></div>
<p>With this code in place, our controller will now have all the products inside the variable <code class="language-plaintext highlighter-rouge">ctrl.products</code>.  So how do we display this?  Well, since we set the templateUrl in the application router, we need to create that file.  So, now I go ahead and make a file called <code class="language-plaintext highlighter-rouge">index.html</code> located inside the <code class="language-plaintext highlighter-rouge">app/assets/javascripts/templates/products</code> directory.  Next, I need to edit that <code class="language-plaintext highlighter-rouge">index.html</code> file to display some of the product attributes.</p>

<div class="language-html highlighter-rouge"><div class="highlight"><pre class="highlight"><code>  <span class="nt">&lt;ul</span> <span class="na">ng-controller=</span><span class="s">"inventory"</span><span class="nt">&gt;</span>
    <span class="nt">&lt;li</span> <span class="na">ng-repeat=</span><span class="s">"product in inventory.products"</span> <span class="na">id=</span><span class="s">""</span> <span class="na">name=</span><span class="s">"product.name"</span><span class="nt">&gt;</span>
      , , 
    <span class="nt">&lt;/li&gt;</span>
  <span class="nt">&lt;/ul&gt;</span>
</code></pre></div></div>

<p>Since I already mounted the application to the html element, I needed to go ahead and declare which controller I’m using with the <code class="language-plaintext highlighter-rouge">ng-controller</code> directive.  With this defined, the <code class="language-plaintext highlighter-rouge">products/index.html</code> file will be loaded into the browser DOM. The HTML in the example above uses an Angular directive <a href="https://docs.angularjs.org/api/ng/directive/ngRepeat">ng-repeat</a> which will iterate through all the items in a collection.  In this case, it is goes through all the products and makes an instance variable <code class="language-plaintext highlighter-rouge">product</code> which allows me to access various attributes which I can display on the page.</p>

<p>Now that everything is working and displaying on the page, it’s time to conclude this series.  I hope you learned something, because I know I learned a lot while trying to explain how to create and Angular application.</p>]]></content><author><name></name></author><summary type="html"><![CDATA[This is the third of a three part series about the insights I gained while building my first AngularJS application using Ruby on Rails in the back-end. This particular post is about setting up the front-end templates and interacting with the Rails back end using Angular factories. There are almost certainly better ways to do some of these things, but this is how I did it and what I learned.]]></summary></entry><entry><title type="html">Building an Angular Application on a Rails Backend: Part 2</title><link href="https://zacbaston.com/rails-angular-app-part-2/" rel="alternate" type="text/html" title="Building an Angular Application on a Rails Backend: Part 2" /><published>2016-09-16T00:00:00+00:00</published><updated>2016-09-16T00:00:00+00:00</updated><id>https://zacbaston.com/rails-angular-app-part-2</id><content type="html" xml:base="https://zacbaston.com/rails-angular-app-part-2/"><![CDATA[<p>This is the second of a three part series about the insights I gained while building my first AngularJS application using Ruby on Rails in the back-end. This particular post is about hooking up Angular to the Rails API. There are almost certainly better ways to do some of these things, but this is how I did it and what I learned.</p>

<hr />

<p>In the last section I provided an example of how a single controller method could respond with JSON data to a request.  Let’s pretend that concept was applied to the entire set of controller actions so that I now have a fully functioning CRUD JSON API.  The next steps needed to create an Angular application will be: including the Angular source file, creating and mounting the application, and building a controller.</p>

<p>There are two quick and easy ways to add the AngularJS source file to a Ruby on Rails application.  The first and probably more Rails way is to simply add <a href="https://github.com/hiravgandhi/angularjs-rails">AngularJS Ruby gem</a> to the Gemfile by adding the line <code class="language-plaintext highlighter-rouge">gem 'angularjs-rails'</code>. Then you will need to add this line to the application.js file <code class="language-plaintext highlighter-rouge">//= require angular</code>, located in <code class="language-plaintext highlighter-rouge">app/assets/javascripts</code>.  Finally, you will have to install it via the command line using Bundler, simply by typing <code class="language-plaintext highlighter-rouge">bundler install</code> into the prompt.</p>

<p>The other way requires a visit to <a href="https://angularjs.org/">https://angularjs.org/</a> to download the actual source file.  Once the file is downloaded, it can be placed in the same directory mentioned above, <code class="language-plaintext highlighter-rouge">app/assets/javascripts</code>, and then we’ll have to require it in the application.js file as well using the same code: <code class="language-plaintext highlighter-rouge">//= require angular</code>.</p>

<p>With Angular now “installed”, the next step is to initialize an Angular app module.  This is accomplished by creating a directory within that same <code class="language-plaintext highlighter-rouge">javascripts</code> directory to hold all the Angular code and it’s a standard to simply call that folder <code class="language-plaintext highlighter-rouge">app</code>.  Next up is to actually create an application file with code called <code class="language-plaintext highlighter-rouge">app.js</code>.  Now to initialize the app, we need to write some code similar to what’s below:</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nx">angular</span>
  <span class="p">.</span><span class="nf">module</span><span class="p">(</span><span class="dl">'</span><span class="s1">trackazon</span><span class="dl">'</span><span class="p">,</span> <span class="p">[]);</span>
</code></pre></div></div>
<p>Here I created an app and the first argument is the name of the app, while the second argument is an array of modules to include in the app.  Since I’m just demonstrating a basic app, I didn’t include any modules, but there are tons available which are used regularly and you can find a list of them here (http://ngmodules.org/)[http://ngmodules.org/].</p>

<p>The next step is to mount (or bootstrap) the app to it’s root element of the HTML using the directive <code class="language-plaintext highlighter-rouge">ng-app</code>.  This can be accomplished easily by navigating to the Rails application template file located here: <code class="language-plaintext highlighter-rouge">app/views/application.html.erb</code>.  Here we’re just going to add an attribute to an already existing HTML element.  I typically bootstrap the application to the body attribute like this <code class="language-plaintext highlighter-rouge">&lt;body ng-app="trackazon"&gt;</code>, but I often see it mounted to the HTML element as such: <code class="language-plaintext highlighter-rouge">&lt;HTML ng-app="trackazon"&gt;</code>.</p>

<p>At this point, I have a functioning Angular app (WOOHOO!), BUT it doesn’t do anything!  I could simply add code to what I wrote in the <code class="language-plaintext highlighter-rouge">app.js</code> file, however going down that route could end up being a huge pain later when I have to constantly scroll throughout a huge monolithic code base to find what I’m looking for.</p>

<p>The way I was taught is to separate the various parts (controllers, services, directives, filters, etc) of the Angular app into their own directories.  And within each of those directories, it is wise to separate logical units into their own files.  For example, I’m going to make a file called <code class="language-plaintext highlighter-rouge">controllers</code> and within it will be all of the controllers. In the context of this application a file will be created called <code class="language-plaintext highlighter-rouge">InventoryController.js</code>.  The quickest way to get a simple controller up and working is by adding the code below to the file:</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nx">angular</span>
  <span class="p">.</span><span class="nf">module</span><span class="p">(</span><span class="dl">'</span><span class="s1">trackazon</span><span class="dl">'</span><span class="p">)</span>
  <span class="p">.</span><span class="nf">controller</span><span class="p">(</span><span class="dl">'</span><span class="s1">InventoryController</span><span class="dl">'</span><span class="p">,</span> <span class="kd">function</span><span class="p">(</span><span class="nx">$scope</span><span class="p">)</span> <span class="p">{</span>

    <span class="nx">$scope</span><span class="p">.</span><span class="nx">test</span> <span class="o">=</span> <span class="dl">"</span><span class="s2">Some test text</span><span class="dl">"</span><span class="p">;</span>
  <span class="p">});</span>

</code></pre></div></div>
<p>Here I created a controller called InventoryController and mounted it to the application.  In this example, the controller takes in one argument called <code class="language-plaintext highlighter-rouge">$scope</code>. <code class="language-plaintext highlighter-rouge">$scope</code> is the convention used by Angular to hold all the variables, functions, and expressions available in the current context.  In this example, I created a string variable called test which can then be displayed anywhere within the application using the Angular syntax ``.</p>

<p>To review, I discussed how to setup Angular and get it running within a Rails application. In the next segment of this series, I’m going to show how to use AngularJS to create customized views and send/ retrieve data to the Rails backend.</p>]]></content><author><name></name></author><summary type="html"><![CDATA[This is the second of a three part series about the insights I gained while building my first AngularJS application using Ruby on Rails in the back-end. This particular post is about hooking up Angular to the Rails API. There are almost certainly better ways to do some of these things, but this is how I did it and what I learned.]]></summary></entry><entry><title type="html">Building an Angular Application on a Rails Backend: Part 1</title><link href="https://zacbaston.com/rails-angular-app-part-1/" rel="alternate" type="text/html" title="Building an Angular Application on a Rails Backend: Part 1" /><published>2016-08-25T00:00:00+00:00</published><updated>2016-08-25T00:00:00+00:00</updated><id>https://zacbaston.com/rails-angular-app-part-1</id><content type="html" xml:base="https://zacbaston.com/rails-angular-app-part-1/"><![CDATA[<p>This is the first of a three part series about the insights I gained while building my first AngularJS application using Ruby on Rails in the backend. This particular post is about the Rails back end and retrieving JSON data. There are almost certainly better ways to do some of these things, but this is how I did it and what I learned.</p>

<hr />

<p>Building a Ruby on Rails application often involves some “magic”, as it’s often called.  One piece of this magic is involved with how a controller action automatically knows to render a view that shares the correct folder and name of that action.  For example, if I had a ProductsController with an index action, Rails would look for a file called <code class="language-plaintext highlighter-rouge">index.html.erb</code> located in a folder named <code class="language-plaintext highlighter-rouge">product</code> nested within the <code class="language-plaintext highlighter-rouge">app/views</code> directory.  This works great for a standard application, but if I wanted to add AJAX functionality I would need to find a different method since parsing an html document and sussing out all the needed parts would quickly become overwhelming.</p>

<p>One way to deal with hooking up a front end JavaScript framework to the Rails back end, is to have the controller actions return JSON data and then use JavaScript to parse that data.  Using this method can make it easier to add AJAX functionality without triggering a complete page reload, which makes for a much smoother user experience.</p>

<p>Let’s now go back to that ProductsController I mentioned earlier.  A very simple version of that controller could look like this:</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code>  <span class="k">class</span> <span class="nc">ProductsController</span> <span class="o">&lt;</span> <span class="no">ApplicationController</span>
    <span class="k">def</span> <span class="nf">index</span>
      <span class="vi">@products</span> <span class="o">=</span> <span class="no">Product</span><span class="p">.</span><span class="nf">all</span>
    <span class="k">end</span>

    <span class="k">def</span> <span class="nf">show</span>
      <span class="vi">@product</span> <span class="o">=</span> <span class="no">Product</span><span class="p">.</span><span class="nf">find</span><span class="p">(</span><span class="n">params</span><span class="p">[</span><span class="ss">:id</span><span class="p">])</span>
    <span class="k">end</span>

    <span class="k">def</span> <span class="nf">new</span>
      <span class="vi">@product</span> <span class="o">=</span> <span class="no">Product</span><span class="p">.</span><span class="nf">new</span>
    <span class="k">end</span>

    <span class="k">def</span> <span class="nf">create</span>
      <span class="vi">@product</span> <span class="o">=</span> <span class="no">Product</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="n">product_params</span><span class="p">)</span>

      <span class="k">if</span> <span class="vi">@product</span><span class="p">.</span><span class="nf">save</span>
        <span class="n">flash</span><span class="p">[</span><span class="ss">:success</span><span class="p">]</span> <span class="o">=</span> <span class="s2">"Product created!"</span>
        <span class="n">redirect_to</span> <span class="vi">@product</span>
      <span class="k">else</span>
        <span class="n">render</span> <span class="s1">'new'</span>
      <span class="k">end</span>
    <span class="k">end</span>

    <span class="k">def</span> <span class="nf">edit</span>
      <span class="vi">@product</span> <span class="o">=</span> <span class="no">Product</span><span class="p">.</span><span class="nf">find</span><span class="p">(</span><span class="n">params</span><span class="p">[</span><span class="ss">:id</span><span class="p">])</span>
    <span class="k">end</span>

    <span class="k">def</span> <span class="nf">update</span>
      <span class="vi">@product</span> <span class="o">=</span> <span class="no">Product</span><span class="p">.</span><span class="nf">find</span><span class="p">(</span><span class="n">params</span><span class="p">[</span><span class="ss">:id</span><span class="p">])</span>

      <span class="k">if</span> <span class="vi">@product</span><span class="p">.</span><span class="nf">update_attributes</span><span class="p">(</span><span class="n">car_params</span><span class="p">)</span>
        <span class="n">redirect_to</span> <span class="vi">@product</span>
      <span class="k">else</span>
        <span class="n">render</span> <span class="s1">'edit'</span>
      <span class="k">end</span>
    <span class="k">end</span>

    <span class="k">def</span> <span class="nf">destroy</span>
      <span class="no">Product</span><span class="p">.</span><span class="nf">find</span><span class="p">(</span><span class="n">params</span><span class="p">[</span><span class="ss">:id</span><span class="p">]).</span><span class="nf">destroy</span>
      <span class="n">redirect_to</span> <span class="n">products_path</span>
    <span class="k">end</span>

    <span class="kp">private</span>
      <span class="k">def</span> <span class="nf">product_params</span>
        <span class="n">params</span><span class="p">.</span><span class="nf">require</span><span class="p">(</span><span class="ss">:product</span><span class="p">).</span><span class="nf">permit</span><span class="p">(</span><span class="ss">:name</span><span class="p">,</span> <span class="ss">:item_price</span><span class="p">,</span> <span class="ss">:sell_price</span><span class="p">,</span> <span class="ss">:quantity</span><span class="p">)</span>
      <span class="k">end</span>
  <span class="k">end</span>
</code></pre></div></div>
<p>There’s nothing too out of the ordinary in there, sure it could be more complex but I’m trying to keep this relatively basic.  Each controller action will return a string of HTML which the browser will then render on the page for the user to view.</p>

<p>To upgrade this application into a single page app (SPA), I have to change the output of each of those controller actions to return JSON.  The easiest and quickest way to change the output is using the powerful <code class="language-plaintext highlighter-rouge">render</code> method provided via the <a href="http://guides.rubyonrails.org/layouts_and_rendering.html#using-render">ActionController::Base class</a>.  The <code class="language-plaintext highlighter-rouge">render</code> method can be used to display a variety of files and file types, such as simple templates, HTML, plain text, XML, and even the coveted JSON.</p>

<p>For example, looking at the <code class="language-plaintext highlighter-rouge">Products#index</code> action, it’s very simple to change the output like below:</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code>  <span class="k">def</span> <span class="nf">index</span>
    <span class="vi">@products</span> <span class="o">=</span> <span class="no">Product</span><span class="p">.</span><span class="nf">all</span>

    <span class="n">render</span> <span class="ss">json: </span><span class="vi">@products</span>
  <span class="k">end</span>
</code></pre></div></div>
<p>This works great for what we need to setup a SPA, but in order to make the application extremely flexible, it could be valuable to have the controller return multiple file types.  Rails has another method nested inside ActionController called <code class="language-plaintext highlighter-rouge">respond_to</code> which provides this functionality.  This method will examine the server request and depending on the file type of that request, it will provide a return value of similar filetype.  In the example below, the browser would be provided a response in kind with the request.  So if it was <code class="language-plaintext highlighter-rouge">/products.json</code>, the response would be JSON; if <code class="language-plaintext highlighter-rouge">/products.xml</code>, the response XML.</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code>  <span class="k">def</span> <span class="nf">index</span>
    <span class="vi">@products</span> <span class="o">=</span> <span class="no">Products</span><span class="p">.</span><span class="nf">all</span>

    <span class="n">respond_to</span> <span class="k">do</span> <span class="o">|</span><span class="nb">format</span><span class="o">|</span>
      <span class="nb">format</span><span class="p">.</span><span class="nf">html</span> <span class="p">{</span> <span class="n">render</span> <span class="ss">:index</span> <span class="p">}</span>
      <span class="nb">format</span><span class="p">.</span><span class="nf">json</span> <span class="p">{</span> <span class="n">render</span> <span class="ss">json: </span><span class="vi">@products</span> <span class="p">}</span>
      <span class="nb">format</span><span class="p">.</span><span class="nf">xml</span> <span class="p">{</span> <span class="n">render</span> <span class="ss">xml: </span><span class="vi">@products</span> <span class="p">}</span>
    <span class="k">end</span>
  <span class="k">end</span>
</code></pre></div></div>
<p>Once again, this provides the functionality to create a SPA already, but while completing my project, I found of another way of metaprogramming the response like below.  This might not be as readable as the above format, it is certainly much more maintanable code since you only have to add the format type as an input to the <code class="language-plaintext highlighter-rouge">.any</code> block.</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code>  <span class="k">def</span> <span class="nf">index</span>
    <span class="vi">@products</span> <span class="o">=</span> <span class="no">Products</span><span class="p">.</span><span class="nf">all</span>

    <span class="n">respond_to</span> <span class="k">do</span> <span class="o">|</span><span class="nb">format</span><span class="o">|</span>
      <span class="nb">format</span><span class="p">.</span><span class="nf">html</span> <span class="p">{</span> <span class="n">render</span> <span class="ss">:index</span> <span class="p">}</span>
      <span class="nb">format</span><span class="p">.</span><span class="nf">any</span><span class="p">(</span><span class="ss">:xml</span><span class="p">,</span> <span class="ss">:json</span><span class="p">,</span> <span class="ss">:text</span><span class="p">)</span> <span class="p">{</span> <span class="n">render</span> <span class="n">request</span><span class="p">.</span><span class="nf">format</span><span class="p">.</span><span class="nf">to_sym</span> <span class="o">=&gt;</span> <span class="vi">@products</span> <span class="p">}</span>
    <span class="k">end</span>
  <span class="k">end</span>
</code></pre></div></div>
<p>I recommend checking out this  <a href="http://apidock.com/rails/ActionController/MimeResponds/respond_to">respond_to</a> documentation to learn even more.</p>

<p>In the next segment of this series, I’m going to show how to setup AngularJS on the front end of a Rails application and get it up and running.</p>]]></content><author><name></name></author><summary type="html"><![CDATA[This is the first of a three part series about the insights I gained while building my first AngularJS application using Ruby on Rails in the backend. This particular post is about the Rails back end and retrieving JSON data. There are almost certainly better ways to do some of these things, but this is how I did it and what I learned.]]></summary></entry><entry><title type="html">jQuery AJAX with Rails</title><link href="https://zacbaston.com/rails-ajax-jquery/" rel="alternate" type="text/html" title="jQuery AJAX with Rails" /><published>2016-07-26T00:00:00+00:00</published><updated>2016-07-26T00:00:00+00:00</updated><id>https://zacbaston.com/rails-ajax-jquery</id><content type="html" xml:base="https://zacbaston.com/rails-ajax-jquery/"><![CDATA[<p>In the <a href="http://zacscodingclub.github.io/display-errors-rails-activerecord-errors/">last blog post</a>, I talked about building a basic Rails app and some of the things I learned along the way.  Today, I’m going to look at what happened along the way when I added a few AJAXy things to that app.</p>

<p>Getting started with AJAX on a Rails app can be a bit confusing, but once you learn a few things, it should be easier to figure stuff out.  One of the first things to know is that Ruby is going to return a string of HTML with it’s standard setup.  To get going, I added the <a href="https://github.com/rails-api/active_model_serializers">active_model_serializer</a> gem to my project using the instructions in the repo.  This will add another generator to Rails which I could call using <code class="language-plaintext highlighter-rouge">rails generate serializer beer</code>.  This creates a new file (<a href="https://github.com/zacscodingclub/beer-me/blob/34d4ebc71d2d485ec276e8e30e3bc8da916e3a8b/app/serializers/beer_serializer.rb">beer_serializer.rb</a>) and inside this file is a new class which inherits from <code class="language-plaintext highlighter-rouge">ActiveModel::Serializer</code>.  The second line of this class shows which attributes of a Beer will be converted into JSON.  Each of these attributes becomes a key in the serialized message and the value is set either from a form or a database request. The id attribute is added by default when you use the Rails generator. For example, the BeerSerializer class would create a nicely formatted object like this:</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code>  <span class="p">{</span>
    <span class="dl">"</span><span class="s2">id</span><span class="dl">"</span><span class="p">:</span> <span class="dl">"</span><span class="s2">1</span><span class="dl">"</span><span class="p">,</span>
    <span class="dl">"</span><span class="s2">name</span><span class="dl">"</span><span class="p">:</span> <span class="dl">"</span><span class="s2">Bomb</span><span class="dl">"</span><span class="p">,</span>
    <span class="dl">"</span><span class="s2">style</span><span class="dl">"</span><span class="p">:</span> <span class="dl">"</span><span class="s2">Imperial Stout</span><span class="dl">"</span><span class="p">,</span>
    <span class="dl">"</span><span class="s2">brewery</span><span class="dl">"</span><span class="p">:</span> <span class="dl">"</span><span class="s2">Prairie</span><span class="dl">"</span>
  <span class="p">}</span>
</code></pre></div></div>
<p>Knowing that the objects return from serialization in this consistent format really helps me save time later.  There are other ways to get to this point, but this is very simple and requires</p>

<p>So with active model serializer in place, everything works right?!?  Well not exactly, at this point the Rails application is still going to return a string of HTML for each request.  To change that, we need to change some code in the BeersController.  Below are three examples of controller actions and what a developer should expect from these actions.</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code>  <span class="c1"># This is the basic Rails controller action.  This grabs some data out of the</span>
  <span class="c1"># databas and then defaults to rendering the index view in the beers folder.</span>
  <span class="k">class</span> <span class="nc">BeersController</span> <span class="o">&lt;</span> <span class="no">ApplicationController</span>
    <span class="k">def</span> <span class="nf">index</span>
      <span class="vi">@beers</span> <span class="o">=</span> <span class="no">Beer</span><span class="p">.</span><span class="nf">all</span>
    <span class="k">end</span>
  <span class="k">end</span>

  <span class="c1"># Very similar to the one above, BUT (and it's a huge but)</span>
  <span class="c1"># this will only return JSON!</span>
  <span class="k">class</span> <span class="nc">BeersController</span> <span class="o">&lt;</span> <span class="no">ApplicationController</span>
    <span class="k">def</span> <span class="nf">index</span>
      <span class="vi">@beers</span> <span class="o">=</span> <span class="no">Beer</span><span class="p">.</span><span class="nf">all</span>

      <span class="n">render</span> <span class="ss">json: </span><span class="vi">@beers</span>
    <span class="k">end</span>
  <span class="k">end</span>

  <span class="c1"># And finally, this is a more adaptable controller action which is like what I</span>
  <span class="c1"># used in the project.  This calls a respond_to block passing in the format of</span>
  <span class="c1"># the web request, so if the request was simply 'beers/index', it would</span>
  <span class="c1"># return HTML.  However, if the request was 'beers/index.json', this will</span>
  <span class="c1"># return JSON similar to what I showed above.</span>
  <span class="k">class</span> <span class="nc">BeersController</span> <span class="o">&lt;</span> <span class="no">ApplicationController</span>
    <span class="k">def</span> <span class="nf">index</span>
      <span class="vi">@beers</span> <span class="o">=</span> <span class="no">Beer</span><span class="p">.</span><span class="nf">all</span>

      <span class="n">respond_to</span> <span class="k">do</span> <span class="o">|</span><span class="n">f</span><span class="o">|</span>
        <span class="n">f</span><span class="p">.</span><span class="nf">html</span> <span class="p">{</span> <span class="n">render</span> <span class="ss">:index</span> <span class="p">}</span>
        <span class="n">f</span><span class="p">.</span><span class="nf">json</span> <span class="p">{</span> <span class="n">render</span> <span class="ss">json: </span><span class="vi">@beers</span> <span class="p">}</span>
      <span class="k">end</span>
    <span class="k">end</span>
  <span class="k">end</span>
</code></pre></div></div>
<p>This concept can be applied throughout all of the actions within the BeersController to create a RESTful API.</p>

<p>Now that the back end is setup, we can finally use jQuery to add some AJAX functionality.  Since I only provided one API endpoint in the example above, I’ll show a simple HTTP Get request.  With the correct controller code, it is very easy to make this code extend to all the other HTTP requests as well.  Check out the official documentation for jQuery <a href="http://api.jquery.com/jquery.ajax/">$.ajax</a> for more information.</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code>  <span class="kd">function</span> <span class="nf">getBeers</span><span class="p">()</span> <span class="p">{</span>
    <span class="nx">$</span><span class="p">.</span><span class="nf">get</span><span class="p">(</span><span class="dl">'</span><span class="s1">/beers</span><span class="dl">'</span> <span class="o">+</span> <span class="dl">'</span><span class="s1">.json</span><span class="dl">'</span><span class="p">,</span> <span class="kd">function</span><span class="p">(</span><span class="nx">data</span><span class="p">)</span> <span class="p">{</span>
      <span class="c1">// whatever you want to happen after a request</span>
      <span class="nf">processBeers</span><span class="p">(</span><span class="nx">data</span><span class="p">);</span>
    <span class="p">});</span>
  <span class="p">}</span>
</code></pre></div></div>
<p>This is a very basic request which has two parameters.  The first is a route and the second is a callback function. In this example, we have an anonymous callback function with the response being the argument.  This response is a variable called data and is a JSON object! There are a few other options which can be chained on to a <a href="https://api.jquery.com/jquery.get/">$.get request</a>, which include .done, .fail, and .always, so go check them out.  Now that we are getting a JSON object as a response, we can pass that data into another function which has been created to handle the display portion of the request.</p>

<p>In this blog, I just showed one simple example, but this technique can be translated all throughout a Rails apps controller actions.  In fact, I can create an entire CRUD API using these methods! The video below shows how a user would interact with a new AJAX UI in the context of BeerMe application. In the future, I’ll go delve deeper into creating a more amazing API and using Angular on the front end!</p>

<p><a href="http://www.youtube.com/watch?v=n1HEZfjsTMo"><img src="http://img.youtube.com/vi/n1HEZfjsTMo/0.jpg" alt="Beer Me - Rails App with Added AJAX!! " /></a></p>]]></content><author><name></name></author><summary type="html"><![CDATA[In the last blog post, I talked about building a basic Rails app and some of the things I learned along the way. Today, I’m going to look at what happened along the way when I added a few AJAXy things to that app.]]></summary></entry><entry><title type="html">Displaying ActiveRecord Errors in Views</title><link href="https://zacbaston.com/display-errors-rails-activerecord-errors/" rel="alternate" type="text/html" title="Displaying ActiveRecord Errors in Views" /><published>2016-07-09T00:00:00+00:00</published><updated>2016-07-09T00:00:00+00:00</updated><id>https://zacbaston.com/display-errors-rails-activerecord-errors</id><content type="html" xml:base="https://zacbaston.com/display-errors-rails-activerecord-errors/"><![CDATA[<p>If you ever build even a simple web application, one thing you’ll have to figure out is how to display error messages to a user.  My experience with errors has mostly been within the context of using Ruby on Rails and ActiveRecord, specifically validations. <a href="http://guides.rubyonrails.org/active_record_validations.html">ActiveRecord Validations</a> are a bunch of helper methods which ensure that “bad” data doesn’t make it into a database.  As a programmer, I can even create my own custom validations which may have specific logic associated with them.  That is kind of a simplification, as the ActiveRecord Validations are just a smaller part of the complete ORM which seems like Rails magic.</p>

<p>Under the hood of ActiveRecord Validations is a class called <code class="language-plaintext highlighter-rouge">ActivRecordError</code>, which inherits from the <code class="language-plaintext highlighter-rouge">StandardError</code> class. The way we access those errors as a programmer is through the resource or model we’re trying to create.  For example, if we have a Ruby class which inherits from ActiveRecord, we can first find out if we have any errors by calling <code class="language-plaintext highlighter-rouge">#valid</code> on the instance of the class.</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code>  <span class="k">class</span> <span class="nc">User</span> <span class="o">&lt;</span> <span class="no">ActiveRecord</span><span class="o">::</span><span class="no">Base</span>
    <span class="n">validates</span> <span class="ss">:name</span><span class="p">,</span> <span class="ss">presence: </span><span class="kp">true</span><span class="p">,</span> <span class="ss">uniqueness: </span><span class="kp">true</span>
  <span class="k">end</span>

  <span class="vi">@user</span> <span class="o">=</span> <span class="no">User</span><span class="p">.</span><span class="nf">new</span>
  <span class="vi">@user</span><span class="p">.</span><span class="nf">valid?</span> <span class="c1"># =&gt; false</span>
  <span class="c1"># or</span>
  <span class="vi">@user</span><span class="p">.</span><span class="nf">invalid?</span> <span class="c1"># =&gt; true</span>

  <span class="c1"># Now, if we know that this instance of the User class is not valid, it's very easy to access the whole ActiveRecord errors object by simply typing:</span>
  <span class="vi">@user</span><span class="p">.</span><span class="nf">errors</span>

  <span class="o">=&gt;</span> <span class="c1">#&lt;ActiveModel::Errors:0x007fdd5b2248f0 @base=#&lt;User id: nil, name: nil&gt;, @messages={:name=&gt;["can't be blank"]}&gt;</span>

  <span class="c1"># But we don't want that, we just want the messages.</span>

  <span class="vi">@user</span><span class="p">.</span><span class="nf">errors</span><span class="p">.</span><span class="nf">messages</span>
  <span class="o">=&gt;</span> <span class="c1">#{:name=&gt;["can't be blank"]</span>
</code></pre></div></div>

<p>This return value is a hash in which each key is object’s attribute and the value is an array of strings.  This is really helpful because it would not be difficult to iterate over each key-value pair in this hash and output a string. Instead of having to figure that all out though, Rails provides us a little magic and we can use <code class="language-plaintext highlighter-rouge">@user.errors.full_messages</code> to construct those error messages and return them as an array, like this:</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code>  <span class="vi">@user</span><span class="p">.</span><span class="nf">errors</span><span class="p">.</span><span class="nf">full_messages</span>
  <span class="o">=&gt;</span> <span class="p">[</span><span class="s2">"Name can't be blank"</span><span class="p">]</span>
</code></pre></div></div>

<p>That’s awesome!  Now we have a very handy way to access any errors on objects that may exist in our application.  For the rest of the blog, I’m going to get more specific into how I dealt with errors in my most recent application <a href="https://github.com/zacscodingclub/beer-me">Beer Me</a>.  This application is pretty simple and only has three models: User, Beer, and CheckIn.  A user has many check ins and has many beers through check ins, the opposite is true of a beer that has many check ins and many users through check ins, and finally a check in belongs to a user and belongs to a beer.  The code below show the specific validations I have in place for each class. These are not complex validations and they really don’t have to be.  They just need to be in place to ensure data integrity.</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code>  <span class="k">class</span> <span class="nc">User</span> <span class="o">&lt;</span> <span class="no">ActiveRecord</span><span class="o">::</span><span class="no">Base</span>
    <span class="n">validates</span> <span class="ss">:username</span><span class="p">,</span> <span class="ss">presence: </span><span class="kp">true</span><span class="p">,</span> <span class="ss">uniqueness: </span><span class="kp">true</span>
    <span class="n">validates</span> <span class="ss">:first_name</span><span class="p">,</span> <span class="ss">presence: </span><span class="kp">true</span>
    <span class="n">validates</span> <span class="ss">:last_name</span><span class="p">,</span> <span class="ss">presence: </span><span class="kp">true</span>

    <span class="c1"># Include default devise modules. Others available are:</span>
    <span class="c1"># :confirmable, :lockable, :timeoutable and :omniauthable</span>
    <span class="n">devise</span> <span class="ss">:database_authenticatable</span><span class="p">,</span> <span class="ss">:registerable</span><span class="p">,</span> <span class="ss">:trackable</span><span class="p">,</span>
           <span class="ss">:validatable</span><span class="p">,</span><span class="ss">:omniauthable</span><span class="p">,</span> <span class="ss">:omniauth_providers</span> <span class="o">=&gt;</span> <span class="p">[</span><span class="ss">:facebook</span><span class="p">]</span>
  <span class="k">end</span>
  <span class="o">...</span>
  <span class="k">class</span> <span class="nc">Beer</span> <span class="o">&lt;</span> <span class="no">ActiveRecord</span><span class="o">::</span><span class="no">Base</span>
    <span class="n">validates</span> <span class="ss">:name</span><span class="p">,</span> <span class="ss">presence: </span><span class="kp">true</span><span class="p">,</span> <span class="ss">uniqueness: </span><span class="kp">true</span>
    <span class="n">validates</span> <span class="ss">:brewery</span><span class="p">,</span> <span class="ss">presence: </span><span class="kp">true</span>
    <span class="n">validates</span> <span class="ss">:style</span><span class="p">,</span> <span class="ss">presence: </span><span class="kp">true</span>
  <span class="k">end</span>
  <span class="o">...</span>
  <span class="k">class</span> <span class="nc">CheckIn</span> <span class="o">&lt;</span> <span class="no">ActiveRecord</span><span class="o">::</span><span class="no">Base</span>
    <span class="n">validates</span> <span class="ss">:beer_id</span><span class="p">,</span> <span class="ss">presence: </span><span class="kp">true</span>
    <span class="n">validates</span> <span class="ss">:rating</span><span class="p">,</span> <span class="ss">presence: </span><span class="kp">true</span><span class="p">,</span> <span class="ss">inclusion: </span><span class="mi">0</span><span class="o">..</span><span class="mi">10</span>
  <span class="k">end</span>
</code></pre></div></div>

<p>For the User class, I included all the <a href="https://github.com/plataformatec/devise">Devise macros</a> since they provide some validations as well.</p>

<p>Now since we have all these validations in place and I earlier broke down the data type and structure of an ActiveRecord error, I can now show you a very simple way to display them within the view.  I hinted at these steps earlier, so hopefully they will be easy to remember.  First thing you want to do is check to see if the object is valid, if it isn’t, then you can create an unordered with HTML and iterate through each of the <code class="language-plaintext highlighter-rouge">.full_messages</code>, adding the full message as list items. See example:</p>

<div class="language-html highlighter-rouge"><div class="highlight"><pre class="highlight"><code>  <span class="nt">&lt;</span><span class="err">%</span> <span class="na">if</span> <span class="err">@</span><span class="na">user.invalid</span><span class="err">?</span> <span class="err">%</span><span class="nt">&gt;</span>
    <span class="nt">&lt;ul&gt;</span>
      <span class="nt">&lt;</span><span class="err">%</span> <span class="err">@</span><span class="na">user.errors.full_messages.each</span> <span class="na">do</span> <span class="err">|</span><span class="na">message</span><span class="err">|</span> <span class="err">%</span><span class="nt">&gt;</span>
        <span class="nt">&lt;li&gt;&lt;</span><span class="err">%=</span> <span class="na">message</span> <span class="err">%</span><span class="nt">&gt;&lt;/li&gt;</span>
      <span class="nt">&lt;</span><span class="err">%</span> <span class="na">end</span> <span class="err">%</span><span class="nt">&gt;</span>
    <span class="nt">&lt;/ul&gt;</span>
  <span class="nt">&lt;</span><span class="err">%</span> <span class="na">end</span> <span class="err">%</span><span class="nt">&gt;</span>
</code></pre></div></div>
<p>Now we should have validations and users in place!  Unfortunately though, I’m using the <a href="http://getbootstrap.com">Bootstrap Framework</a> and these errors look a little plain.  In the next code sample, I am simply adding some stuff to the previous code.  First thing to note is p-tag on line 4.  This uses the Rails Inflector to determine if the word “error” should be plural depending on the number of errors object, and adds a nice little header message to the error.  The other additions to this version are some Bootstrap alert classes to make these messages really stand out to the user.  And lastly on line 3, this simply shows a “x” which the user can click to close the error message box.</p>

<div class="language-html highlighter-rouge"><div class="highlight"><pre class="highlight"><code>  <span class="nt">&lt;</span><span class="err">%</span> <span class="na">if</span> <span class="err">@</span><span class="na">user.valid</span><span class="err">?</span> <span class="err">%</span><span class="nt">&gt;</span>
    <span class="nt">&lt;div</span> <span class="na">class=</span><span class="s">"alert alert-error alert-danger"</span><span class="nt">&gt;</span>
      <span class="nt">&lt;button</span> <span class="na">type=</span><span class="s">"button"</span> <span class="na">class=</span><span class="s">"close"</span> <span class="na">data-dismiss=</span><span class="s">"alert"</span><span class="nt">&gt;</span>x<span class="nt">&lt;/button&gt;</span>
      <span class="nt">&lt;p&gt;&lt;</span><span class="err">%=</span> <span class="na">pluralize</span><span class="err">(@</span><span class="na">user.errors.count</span><span class="err">,</span> <span class="err">"</span><span class="na">error</span><span class="err">")</span> <span class="err">%</span><span class="nt">&gt;</span> stopped us from adding this to the database.<span class="nt">&lt;/p&gt;</span>

      <span class="nt">&lt;ul&gt;</span>
        <span class="nt">&lt;</span><span class="err">%</span> <span class="err">@</span><span class="na">user.errors.full_messages.each</span> <span class="na">do</span> <span class="err">|</span><span class="na">message</span><span class="err">|</span> <span class="err">%</span><span class="nt">&gt;</span>
          <span class="nt">&lt;li&gt;&lt;</span><span class="err">%=</span> <span class="na">message</span> <span class="err">%</span><span class="nt">&gt;&lt;/li&gt;</span>
        <span class="nt">&lt;</span><span class="err">%</span> <span class="na">end</span> <span class="err">%</span><span class="nt">&gt;</span>
      <span class="nt">&lt;/ul&gt;</span>
    <span class="nt">&lt;/div&gt;</span>
  <span class="nt">&lt;</span><span class="err">%</span> <span class="na">end</span> <span class="err">%</span><span class="nt">&gt;</span>
</code></pre></div></div>
<p>At this point, I would be pretty happy with myself and call it a day.  The problem is I have three different classes and multiple different forms, which means I would need to repeat this code at least three times in the User#new, Beer#new, and CheckIn#new pages.  This of course violates the DRY principle (Don’t Repeat Yourself!!!)  Luckily, Rails gives us several ways to refactor this code and I’m going to use an ActionView helper to show these errors wherever I want on my application.</p>

<p>So basically the HTML for all these errors looks the same, except for the instance variable on which we are checking for errors.  One concept that’s already used in Rails is the idea of a resource.  This concept is used by Rails generators when creating new models, controllers, views, routes, and tests for that resource.  I think using that concept of a resource is a great abstraction for the models in my application.  Below is the final helper method I ended up creating and there are comments for each line.</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">module</span> <span class="nn">ApplicationHelper</span>
  <span class="k">def</span> <span class="nf">resource_error_messages</span><span class="p">(</span><span class="n">resource</span><span class="p">)</span>
    <span class="c1"># check to see if the resource doesn't exist or if there are no errors</span>
    <span class="n">no_errors</span> <span class="o">=</span> <span class="n">resource</span><span class="p">.</span><span class="nf">nil?</span> <span class="o">||</span> <span class="n">resource</span><span class="p">.</span><span class="nf">errors</span><span class="p">.</span><span class="nf">empty?</span>
    <span class="c1"># if there are no errors, this helper stops and returns an empty string, which adds nothing to the view</span>
    <span class="k">return</span> <span class="s1">''</span> <span class="k">if</span> <span class="n">no_errors</span>

    <span class="c1"># Similar to above where I am counting the errors, pluralizing if needed, and saving this string as a variable for later use</span>
    <span class="n">num_errors</span> <span class="o">=</span> <span class="n">pluralize</span><span class="p">(</span><span class="n">resource</span><span class="p">.</span><span class="nf">errors</span><span class="p">.</span><span class="nf">full_messages</span><span class="p">.</span><span class="nf">count</span><span class="p">,</span> <span class="s2">"error"</span><span class="p">)</span> <span class="o">+</span> <span class="s2">" stopped us from adding this to the database."</span>
    <span class="c1"># This returns a bunch of list elements with the full message as the text, and then joins them together to create a single string</span>
    <span class="c1"># i.e. "&lt;li&gt;Name can't be blank&lt;/li&gt;&lt;li&gt;Name is too short (minimum is 3 characters)&lt;/li&gt;"</span>
    <span class="n">messages</span> <span class="o">=</span> <span class="n">resource</span><span class="p">.</span><span class="nf">errors</span><span class="p">.</span><span class="nf">full_messages</span><span class="p">.</span><span class="nf">map</span> <span class="p">{</span> <span class="o">|</span><span class="n">msg</span><span class="o">|</span> <span class="n">content_tag</span><span class="p">(</span><span class="ss">:li</span><span class="p">,</span> <span class="n">msg</span><span class="p">)</span> <span class="p">}.</span><span class="nf">join</span>

    <span class="c1"># Here we're creating a html heredoc which interpolates the values we created above into a nicely formatted.</span>
    <span class="c1"># Note the button_tag which took a lot of figuring out how to nest the dismiss attribute within the data hash to work properly</span>
    <span class="n">content</span> <span class="o">=</span> <span class="o">&lt;&lt;-</span><span class="no">HTML</span><span class="sh">
      </span><span class="si">#{</span> <span class="n">content_tag</span> <span class="ss">:p</span><span class="p">,</span> <span class="n">num_errors</span><span class="si">}</span><span class="sh">
      </span><span class="si">#{</span> <span class="n">button_tag</span> <span class="s2">"x"</span><span class="p">,</span> <span class="k">class</span><span class="ss">:"close"</span><span class="p">,</span> <span class="ss">data: </span><span class="p">{</span> <span class="n">dismiss</span><span class="ss">:"alert"</span><span class="si">}</span><span class="sh"> }
      </span><span class="si">#{</span> <span class="n">messages</span><span class="si">}</span><span class="sh">
</span><span class="no">    HTML</span>

    <span class="c1"># This takes the content html we just created and then adds it to a larger div with the correct bootstrap classes</span>
    <span class="n">html</span> <span class="o">=</span> <span class="o">&lt;&lt;-</span><span class="no">HTML</span><span class="sh">
      </span><span class="si">#{</span> <span class="n">content_tag</span> <span class="ss">:div</span><span class="p">,</span> <span class="n">content</span><span class="p">,</span> <span class="k">class</span><span class="ss">:"alert alert-error alert-danger"</span> <span class="si">}</span><span class="sh">
</span><span class="no">    HTML</span>

    <span class="c1"># Here we take that html variable, and use the .html_safe command to ensure that any unwanted characters are escaped by rails before rendering.  It's may not be too useful for this particular purpose, but this is a good practice to follow.</span>
    <span class="n">html</span><span class="p">.</span><span class="nf">html_safe</span>
  <span class="k">end</span>
<span class="k">end</span>
</code></pre></div></div>
<p>Now that the helper exists, we can now call it in views simply by typing <code class="language-plaintext highlighter-rouge">&lt;%= resource_error_messages(resource) %&gt;</code>.
Hopefully there was something of value for you above.  In the video below I give a tour of the user interface and show some interesting portions of the code.  If you’re curious about the code, check out the github repo <a href="https://github.com/zacscodingclub/beer-me">beer-me</a>.</p>

<p><a href="http://www.youtube.com/watch?v=p48-bVaSB9w"><img src="http://img.youtube.com/vi/p48-bVaSB9w/0.jpg" alt="Beer Me Walkthrough Video" /></a></p>]]></content><author><name></name></author><summary type="html"><![CDATA[If you ever build even a simple web application, one thing you’ll have to figure out is how to display error messages to a user. My experience with errors has mostly been within the context of using Ruby on Rails and ActiveRecord, specifically validations. ActiveRecord Validations are a bunch of helper methods which ensure that “bad” data doesn’t make it into a database. As a programmer, I can even create my own custom validations which may have specific logic associated with them. That is kind of a simplification, as the ActiveRecord Validations are just a smaller part of the complete ORM which seems like Rails magic.]]></summary></entry><entry><title type="html">A Sinatra Application Built to Hold My Lecture Notes</title><link href="https://zacbaston.com/lectures-notes-sinatra-app/" rel="alternate" type="text/html" title="A Sinatra Application Built to Hold My Lecture Notes" /><published>2016-06-20T00:00:00+00:00</published><updated>2016-06-20T00:00:00+00:00</updated><id>https://zacbaston.com/lectures-notes-sinatra-app</id><content type="html" xml:base="https://zacbaston.com/lectures-notes-sinatra-app/"><![CDATA[<p>As I continue along the process of becoming a web developer, I am constantly watching videos about various programming concepts.  There are so many lectures, talks, and podcasts coming out every day, I kept wanting to keep track of my notes and various info about these videos.  Since my last post discussed <a href="http://zacscodingclub.github.io/find-a-gym-gem/">my first Ruby gem</a>, and I’m learning to become a web developer, it makes sense that the next step in my learning would be to create a web application to solve my problem.  My first hack of a solution to this issue is a <a href="http://www.sinatrarb.com/">Sinatra</a> application I built called <a href="https://github.com/zacscodingclub/learn-progress-checklist">Learn Progress Checklist</a>.</p>

<p>This project was my first crack at building a custom web app and wiring it up with my data.  And what that really means to me is that I learned a lot about ActiveRecord in the process of building this application.  The two main parts of ActiveRecord that I used most frequently were the migrations and validations.  Honestly, I think the ActiveRecord documentation on the Ruby on Rails website for <a href="http://edgeguides.rubyonrails.org/active_record_migrations.html">Migrations</a> and <a href="http://edgeguides.rubyonrails.org/active_record_validations.html">Validations</a> is amazing!  While troubleshooting the construction of my app, I was constantly referencing back to these guides and learning that I could in fact set column defaults and ensure only the correct data is entering into the database with model validations.  Most of the validations in this app are simple checks to make sure that the data is present as seen in these lines of code from their respective models:</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">Note</span> <span class="o">&lt;</span> <span class="no">ActiveRecord</span><span class="o">::</span><span class="no">Base</span>
  <span class="n">validates_presence_of</span> <span class="ss">:content</span>
<span class="k">end</span>

<span class="k">class</span> <span class="nc">User</span> <span class="o">&lt;</span> <span class="no">ActiveRecord</span><span class="o">::</span><span class="n">base</span>
  <span class="n">validates</span> <span class="ss">:email</span><span class="p">,</span> <span class="ss">presence: </span><span class="kp">true</span><span class="p">,</span> <span class="ss">uniqueness: </span><span class="kp">true</span>
<span class="k">end</span>

</code></pre></div></div>
<p>In this first example, <code class="language-plaintext highlighter-rouge">validates_presence_of</code> is just a macro that builds out some code similar to what is in the second example.  The second example checks to see if the User’s email address is valid by passing in a hash of arguments that the email attribute must pass, that hash is: <code class="language-plaintext highlighter-rouge">{ presence: true, uniqueness: true }</code>.  ActiveRecord validations can be customized to fit the needs of any attribute, so they are a great way to preserve data integrity.</p>

<p>One other thing I want to note is that I built this app just over 2 months ago.  And since then, I’ve been learning this amazing framework called Ruby on Rails.  When I revisited this project to write a blog post, I had forgotten what happened inside a Sinatra controller.  After building out all these CRUD actions in Rails apps, I found it really strange to see the actual routes located within each controller.  I really enjoy the way Rails has that abstracted out in it’s convention over configuration philosophy.</p>

<p><a href="http://www.youtube.com/watch?v=sbhN0W47CSg"><img src="http://img.youtube.com/vi/sbhN0W47CSg/0.jpg" alt="Sinatra Application Walkthrough Video" /></a></p>]]></content><author><name></name></author><summary type="html"><![CDATA[As I continue along the process of becoming a web developer, I am constantly watching videos about various programming concepts. There are so many lectures, talks, and podcasts coming out every day, I kept wanting to keep track of my notes and various info about these videos. Since my last post discussed my first Ruby gem, and I’m learning to become a web developer, it makes sense that the next step in my learning would be to create a web application to solve my problem. My first hack of a solution to this issue is a Sinatra application I built called Learn Progress Checklist.]]></summary></entry><entry><title type="html">Finding a Weightlifting Gym Using a Ruby Gem!</title><link href="https://zacbaston.com/find-a-gym-gem/" rel="alternate" type="text/html" title="Finding a Weightlifting Gym Using a Ruby Gem!" /><published>2016-06-11T00:00:00+00:00</published><updated>2016-06-11T00:00:00+00:00</updated><id>https://zacbaston.com/find-a-gym-gem</id><content type="html" xml:base="https://zacbaston.com/find-a-gym-gem/"><![CDATA[<p>As a student of Flatiron School’s online campus, <a href="https://learn.co/with/zacscodingclub">Learn Verified</a>, the first real project you set forth alone to create is a Ruby Gem.  There are several basic requirements to complete this project which include a few things like building a command line interface for the gem and data for the gem must be provided via scraping or public API.  In this post I’m going to talk about how I decided what to make and the basic structure of my program.  Then at the end I’ll post a video walkthrough to show the interface and some code.</p>

<p>A lot of people have an issue coming up with an idea for what they should create.  To get through that barrier, I recommend thinking about the 3 or 4 things in your life that you spend the most time doing. For me that’s simple because my time is occupied mostly by working, studying code, and weightlifting.  I picked weightlifting since I know a lot about it and it’s fun! Since it’s not likely to find any sort of public API regarding weightlifting (email me if you find any though!), I had to figure out some data I could scrape.</p>

<p>After looking through the <a href="http://usaweightlifting.com">USA Weightlifting</a> website for a little bit, I identified two pieces of relevant content that I could scrape.  The first collection of items I saw were weightlifting events.  These events typically have dates, participants, results, judges, etc.  The second set of data I noticed was the listings of USA Weightlifting certified club gyms <a href="http://www.teamusa.org/usa-weightlifting/clubs-lwc/find-a-club">http://www.teamusa.org/usa-weightlifting/clubs-lwc/find-a-club</a>.  The gyms stood out to me because the page is setup in a very unfriendly manner where the user can only look at gyms by selecting the state in which they are located.  There is no search or other easy lookup method, like a map.</p>

<p>Now that I identified what I was going to scrape, I had to figure out what are the important details of a gym.  To determine those details, I just click through to any state and examine what the webpage tells me about each gym.  Hmmm, OK.  It looks like each Gym will have several attributes which include: name, full address, phone number, director name, and director phone number.</p>

<p>I use <a href="http://bundler.io/">Bundler</a> (a cool program that manages Ruby gems), so creating a gem from scratch is as easy as typing</p>
<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>bundle gem closest_weightlifting_gem
</code></pre></div></div>
<p>This is a handy macro that builds out a basic skeleton of folders and files that is commonly used for a Ruby gems.  If you’re new to Ruby or gems, I highly recommend you read through this helpful tutorial <a href="http://guides.rubygems.org/make-your-own-gem/">RubyGems- Make Your Own Gem</a>.  After that, you’ll what to look through each file and folder and try to figure out what’s going on under the hood, so to speak.  Understanding what is inside each gem and where it’s located within the code base will make you a more productive programmer.  Below is a screenshot of all the files of the current version of my app:</p>

<p><img src="/images/cli_file_structure.png" height="850" width="425" /></p>

<p>Starting at the top, the first thing I see is the <code class="language-plaintext highlighter-rouge">/bin</code> folder.  This holds any executables your program will need to run.  One thing to notice is that there is no file extension on any of the three files within <code class="language-plaintext highlighter-rouge">/bin</code>.  When first creating these files, I had to modify their permissions using <code class="language-plaintext highlighter-rouge">chmod -R 0777 bin/setup</code> in the command line to make this file executable.  So now the terminal can run this file, but I also need to add this small bit of code on the first line so that it knows to use the Ruby interpreter when reading the code contained within each file <code class="language-plaintext highlighter-rouge">#!/usr/bin/env ruby</code>.  Now I can write plain old Ruby syntax within each file and it will work the way I expect!  The three files within <code class="language-plaintext highlighter-rouge">/bin</code> all serve one particular function: <code class="language-plaintext highlighter-rouge">closest-weightlifting-gem</code>: command line interface executable, <code class="language-plaintext highlighter-rouge">console</code>: opens up a <a href="https://github.com/pry/pry">pry console</a> with some data collected to test,  and <code class="language-plaintext highlighter-rouge">setup</code>: basic i and installation of proper dependencies.</p>

<p>The next folder, <code class="language-plaintext highlighter-rouge">/lib</code>, contains one folder with several files and a file called <code class="language-plaintext highlighter-rouge">closest_weightlifting_gem.rb</code>.  This requires all the needed dependencies and then creates a <code class="language-plaintext highlighter-rouge">module</code> with the common namespace that all the files in this program will share: <code class="language-plaintext highlighter-rouge">ClosestWeightliftingGem</code>.  Within the folder are several files and each one represents a specific class that logically separates the concerns of the program.  I don’t really want to get bogged down into the details for each of those files jobs here, but you should know that each file does something simple and hopefully does it well.  The <code class="language-plaintext highlighter-rouge">version.rb</code> file is a gem standard and should be in every Ruby gem.</p>

<p>After that, there is a <code class="language-plaintext highlighter-rouge">/spec</code> folder which is used to hold tests for Ruby’s rspec testing suite.  The <code class="language-plaintext highlighter-rouge">spec_helper.rb</code> file contains setup instructions for testing and the other file should contain tests for your program.  I’m slacking on this right now, but it is on my to-do list.</p>

<p>Now there are several files left in the main folder of the gem and they provide two pieces of info needed, one for Github and the other is administration of the gem.</p>

<ul>
  <li>
    <p><strong>Github</strong> - Several files are there since this is also a <a href="https://github.com/zacscodingclub/closest_weightlifting_gem">Github repository</a>, such as <code class="language-plaintext highlighter-rouge">.gitignore</code>, <code class="language-plaintext highlighter-rouge">LICENSE.txt</code>, <code class="language-plaintext highlighter-rouge">README.md</code>, and <code class="language-plaintext highlighter-rouge">notes.md</code>.  <code class="language-plaintext highlighter-rouge">.gitignore</code> allows me to pick which files I don’t want git to track (see this guide for syntax questions: <a href="https://gist.github.com/octocat/9257657">Some common .gitignore configurations</a>).  <code class="language-plaintext highlighter-rouge">LICENSE.txt</code> was generated with the bundle gem command earlier and places a MIT license within this repo gives permission for other collaborators.  <code class="language-plaintext highlighter-rouge">README.md</code> includes basic installation/setup of the gem, as well as a to-do list for future gem work.  And <code class="language-plaintext highlighter-rouge">notes.md</code> was just some notes I was keeping throughout the process of making the app.</p>
  </li>
  <li>
    <p><strong>Gem Administration</strong> - The first thing I typically look at for Ruby gem info is the <code class="language-plaintext highlighter-rouge">gemspec</code> file, but in an actual gem, it just refers the user to the code in the <code class="language-plaintext highlighter-rouge">closest_weightlifting_gem.gemspec</code> file.  The .gemspec file pieces all the information needed for this gem to run.  It provides basic biographical info about the gem and it’s where I have to include the commands which add dependencies to the code. Other gem admin related files end with <code class="language-plaintext highlighter-rouge">.gem</code> and they provide a record of each version of the gem.</p>
  </li>
  <li>
    <p><strong>Other</strong> - <code class="language-plaintext highlighter-rouge">.rspec</code> includes code which customizes the rspec command line code, whether it be format, color, output, etc.  I typically use the <code class="language-plaintext highlighter-rouge">Rakefile</code> to define tasks which I would use regularly during development.  In this case, I put that into the <code class="language-plaintext highlighter-rouge">/bin/console</code> executable.  And the last file is the <code class="language-plaintext highlighter-rouge">.travis.yml</code> and I had to look that one up.  According to <a href="https://en.wikipedia.org/wiki/Travis_CI">Travis CI - Wikipedia</a>, “This file specifies the programming language used, the desired building and testing environment (including dependencies which must be installed before the software can be built and tested), and various other parameters.” So it sounds like a basic configuration file, but to be honest, I’ve never seen the code inside it until just now.</p>
  </li>
</ul>

<p>Well, with all that said, in the video below I give a tour of the user interface and show some interesting portions of the code.  If you’re curious about the code, check out the github repo <a href="https://github.com/zacscodingclub/closest_weightlifting_gem">closest_weightlifting_gem</a>.</p>

<p><a href="http://www.youtube.com/watch?v=S3jWSZqWviI"><img src="http://img.youtube.com/vi/S3jWSZqWviI/0.jpg" alt="Closest Weightlifting Gem Gym Walkthrough Video" /></a></p>]]></content><author><name></name></author><summary type="html"><![CDATA[As a student of Flatiron School’s online campus, Learn Verified, the first real project you set forth alone to create is a Ruby Gem. There are several basic requirements to complete this project which include a few things like building a command line interface for the gem and data for the gem must be provided via scraping or public API. In this post I’m going to talk about how I decided what to make and the basic structure of my program. Then at the end I’ll post a video walkthrough to show the interface and some code.]]></summary></entry></feed>