Nick TomlinI'm Nick Tomlin, a developer in Chicago. I like JavaScript.http://nick-tomlin.com/
Sun, 03 Dec 2017 00:56:12 +0000Sun, 03 Dec 2017 00:56:12 +0000Jekyll v3.6.2Issues loading dependencies in the Clojure repl<p>I’ve been dusting off my <em>very dusty</em> Clojure parens and recently ran into a head scratcher when attempting to mess around with <a href="https://github.com/cgrand/enlive">enlive</a> in a Clojure repl.</p>
<p>When attempting to follow along tutorial I naively popped open my repl and attempted to require enlive like so:</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(require [net.cgrand.enlive-html :as html])
</code></pre></div></div>
<p>And received the following lovely exception:</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>CompilerException java.lang.ClassNotFoundException: net.cgrand.enlive-html
</code></pre></div></div>
<p>Thanks to <a href="https://stackoverflow.com/a/9811346/1048479">this</a> informative stackoverflow post, I was reminded of the difference between <code class="highlighter-rouge">require</code> nested within the <code class="highlighter-rouge">ns</code> macro and <code class="highlighter-rouge">require</code> run inside of a repl.</p>
<p>The solution is to do the work the <code class="highlighter-rouge">ns</code> macro is doing for you, namely, to quote the vector you are passing to <code class="highlighter-rouge">require</code>:</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(require '[net.cgrand.enlive-html :as html])
(html/text (first (html/select (html/html-resource (java.net.URL. "https://clojure.org")) [:.clj-header-message])))
</code></pre></div></div>
<p><a href="https://8thlight.com/blog/colin-jones/2012/05/22/quoting-without-confusion.html">Quoting without confusion</a> is a good reference here if you (like me) get confused by quotes.</p>
<p>Additionally, for easy <code class="highlighter-rouge">repl</code>ing, it’s probably easier to do this with <code class="highlighter-rouge">use</code> (which will clobber your current namespace but is worth it for hacking) or to stick this all in a file and use the <code class="highlighter-rouge">load</code>/<code class="highlighter-rouge">in-ns</code> combo (more on that <a href="https://www.beyondtechnicallycorrect.com/2013/04/14/loading-and-using-namespaces-in-the-clojure-repl/">here</a>):</p>
<div class="language-clojure highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">; e.g. for src/my_ns.clj</span><span class="w">
</span><span class="c1">; that has a ns of `my-ns`</span><span class="w">
</span><span class="p">(</span><span class="nb">load</span><span class="w"> </span><span class="s">"my_ns"</span><span class="p">)</span><span class="w">
</span><span class="p">(</span><span class="nb">in-ns</span><span class="w"> </span><span class="ss">'my-ns</span><span class="p">)</span><span class="w">
</span><span class="c1">; you can now access variables defined in that namespace</span><span class="w">
</span><span class="p">(</span><span class="nf">my-ns/my-func</span><span class="w"> </span><span class="s">"argc"</span><span class="p">)</span><span class="w">
</span></code></pre></div></div>
<p>Hopefully this helps shortcut someone else. Cheers!</p>
Fri, 10 Nov 2017 00:00:00 +0000http://nick-tomlin.com/2017/11/10/clojure-dependencies-and-lein-repl/
http://nick-tomlin.com/2017/11/10/clojure-dependencies-and-lein-repl/VimL Functions<p>I’ve started a slow descent into the madness that is VimL. One of the things that I’ve found to be initially confusing is how Vim deals with functions. This may be very obvious to some but It caused me enough head scratching to warrant recording some thoughts here.</p>
<details class="tldr">
<summary>Cheatsheet</summary>
<div class="language-viml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c">" All VimL functions must be called</span>
<span class="c">" Operations like assignment</span>
<span class="c">" or passing to another function or built in</span>
<span class="c">" implicitly call a function</span>
<span class="k">let</span> var <span class="p">=</span> MyFunc<span class="p">()</span>
echo MyFunc<span class="p">()</span>
<span class="c">" Otherwise, you _must_ :call a function</span>
<span class="k">call</span> MyFunc<span class="p">()</span>
<span class="c">" You can also store a reference to your function</span>
<span class="k">let</span> FuncRef <span class="p">=</span> <span class="k">function</span><span class="p">(</span><span class="s1">'MyFunc'</span><span class="p">)</span>
<span class="c">" and :call it with arguments or pass it to another function</span>
<span class="k">call</span><span class="p">(</span>FuncRef<span class="p">,</span> <span class="m">1</span><span class="p">,</span> <span class="m">2</span><span class="p">,</span> <span class="m">3</span><span class="p">)</span>
<span class="c">" Or, stringify and execute it</span>
execute <span class="s1">'echo '</span> <span class="p">.</span> string<span class="p">(</span>FuncRef<span class="p">)</span>
<span class="c">" Bonus: Lambdas (vim8+ and neovim) are pretty swank</span>
<span class="k">let</span> MyLambda <span class="p">=</span> <span class="p">{</span> str <span class="p">-&gt;</span> str <span class="p">.</span> <span class="s1">'!'</span> <span class="p">}</span>
echo MyLambda<span class="p">(</span><span class="s1">'yay'</span><span class="p">)</span>
<span class="c">" yay!</span>
echo map<span class="p">([</span><span class="m">1</span><span class="p">,</span> <span class="m">2</span><span class="p">,</span> <span class="m">3</span><span class="p">],</span> <span class="p">{</span> _<span class="p">,</span> val <span class="p">-&gt;</span> val * <span class="m">2</span> <span class="p">})</span>
<span class="c">" [2, 4, 6]</span>
</code></pre></div> </div>
</details>
<h1 id="getting-func-y">Getting func-y</h1>
<p>Having one way to call a function is boring: most languages have a few different ways to invoke a function you or someone you love has defined. Not to be outdone, VimL has some twists of its own related to functions.</p>
<p>Let’s create a very simple function:</p>
<div class="language-viml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c">" All Viml functions must begin with a capitol letter</span>
<span class="k">function</span><span class="p">!</span> Hello<span class="p">(</span>name<span class="p">)</span>
<span class="c">" :wave: Just in case you were wondering</span>
<span class="c">" all named arguments are only available on the magical</span>
<span class="c">" arguments dictionary (a) within the function</span>
<span class="k">return</span> <span class="s2">"Hi "</span> <span class="p">.</span> <span class="nv">a:name</span> <span class="p">.</span> <span class="s2">"!"</span>
<span class="k">endfunction</span>
</code></pre></div></div>
<p>The easiest way to call this function in a script, we could simply assign it to a variable, or pass the result of invoking it to a built in like <code class="highlighter-rouge">echo</code>:</p>
<div class="language-viml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">let</span> greeting <span class="p">=</span> Hello<span class="p">(</span><span class="s1">'bob'</span><span class="p">)</span>
echo greeting
<span class="c">"Hi Bob!"</span>
echo Hello<span class="p">(</span><span class="s1">'bob'</span><span class="p">)</span>
<span class="c">"Hi Bob!"</span>
</code></pre></div></div>
<p>This makes a <em>lot</em> of sense! We’ve always been told that VimL doesn’t make much sense; it feels good to prove people wrong doesn’t it?</p>
<p>But, let’s say we just want the side effects of a function and do not want to deal with whatever it returns. It’d make sense to do the same thing but just not assign it right?</p>
<div class="language-viml highlighter-rouge"><div class="highlight"><pre class="highlight"><code>MySideEffectFunc<span class="p">(</span><span class="s1">'some side effecty argument'</span><span class="p">)</span>
E492<span class="p">:</span> Not an editor command<span class="p">:</span> MySideEffectFunc<span class="p">()</span>
</code></pre></div></div>
<p>Not so fast! VimL has other ideas; while certain built in commands (like <code class="highlighter-rouge">echo</code>) can be invoked, functions cannot simply be called without passing or assigning their value. This is because things like <code class="highlighter-rouge">echo Foo()</code> and <code class="highlighter-rouge">let x = Foo()</code> implicitly evaluate or call any expression they are handed (in this case, the expression being invoking the function <code class="highlighter-rouge">Foo</code>). Since <code class="highlighter-rouge">Foo()</code> isn’t good enough, we need a way to tell VimL to actually call the function.</p>
<p>This is where <a href="http://vimdoc.sourceforge.net/htmldoc/eval.html#:call"><code class="highlighter-rouge">:call</code></a> steps in. <code class="highlighter-rouge">:call</code> calls a function, with up to 20 arguments (because 19 just wasn’t enough), and discards its return value.</p>
<div class="language-viml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">:</span><span class="k">call</span> MySideEffectFunc<span class="p">(</span><span class="s1">'this wooooorks'</span><span class="p">)</span>
</code></pre></div></div>
<p>Call is the <em>the</em> way of calling functions within your plugins, or invoking other functions from ex mode.</p>
<h1 id="show-me-your-references">Show me your references</h1>
<p>Let’s explore another way we can use our functions: references. Let’s take a common example, using <a href="http://vimdoc.sourceforge.net/htmldoc/eval.html#map()"><code class="highlighter-rouge">map</code></a> with a function we’ve previously defined. We can use Vim’s <code class="highlighter-rouge">function</code> keyword to create a funcref (that is a reference to function <em>wink</em> <em>wink</em>) which allows us to pass it to <code class="highlighter-rouge">map</code>, <code class="highlighter-rouge">filter</code>, or another function.</p>
<div class="language-viml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">function</span> Exclaim<span class="p">(</span>idx<span class="p">,</span> name<span class="p">)</span>
<span class="k">return</span> <span class="nv">a:name</span> <span class="p">.</span> <span class="s2">"!"</span>
<span class="k">endfunction</span>
<span class="k">let</span> greetings <span class="p">=</span> <span class="p">[</span><span class="s1">'Hey'</span><span class="p">,</span> <span class="s1">'Howdy'</span><span class="p">,</span> <span class="s1">'Hi'</span><span class="p">]</span>
<span class="k">let</span> exclaimed <span class="p">=</span> map<span class="p">(</span>greetings<span class="p">,</span> <span class="k">function</span><span class="p">(</span><span class="s1">'Exclaim'</span><span class="p">))</span>
echo exclaimed
<span class="c">" ['Hey!', 'Howdy!', 'Hi!']</span>
</code></pre></div></div>
<p>If we wanted to take a more generic function that did not need to be aware of <code class="highlighter-rouge">idx</code>, we could use <code class="highlighter-rouge">string</code>ify our funcref and use <code class="highlighter-rouge">map</code>’s second argument (a string to be <code class="highlighter-rouge">eval</code>d) to invoke our function with the value of each pair we are iterating through:</p>
<div class="language-viml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">function</span> Exclaim<span class="p">(</span>name<span class="p">)</span>
<span class="k">return</span> <span class="nv">a:name</span> <span class="p">.</span> <span class="s2">"!"</span>
<span class="k">endfunction</span>
<span class="k">let</span> greetings <span class="p">=</span> <span class="p">[</span><span class="s1">'Hey'</span><span class="p">,</span> <span class="s1">'Howdy'</span><span class="p">,</span> <span class="s1">'Hi'</span><span class="p">]</span>
<span class="k">let</span> exclaimed <span class="p">=</span> map<span class="p">(</span>greetings<span class="p">,</span> string<span class="p">(</span><span class="k">function</span><span class="p">(</span><span class="s1">'Exclaim'</span><span class="p">))</span> <span class="p">.</span> <span class="p">(</span><span class="s1">'v:val'</span><span class="p">))</span>
echo exclaimed
<span class="c">" ['Hey!', 'Howdy!', 'Hi!']</span>
</code></pre></div></div>
<p>That works, but it’s not very readable. Luckily, more modern versions of Vim have an answer.</p>
<h1 id="lambdas-to-the-rescue">Lambdas to the rescue</h1>
<p>If we, or our intended users, are using vim8+ or neovim, we can use the new lambda syntax to simplify things:</p>
<div class="language-viml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">function</span> Exclaim<span class="p">(</span>name<span class="p">)</span>
<span class="k">return</span> <span class="nv">a:name</span> <span class="p">.</span> <span class="s2">"!"</span>
<span class="k">endfunction</span>
<span class="k">let</span> greetings <span class="p">=</span> <span class="p">[</span><span class="s1">'Hey'</span><span class="p">,</span> <span class="s1">'Howdy'</span><span class="p">,</span> <span class="s1">'Hi'</span><span class="p">]</span>
<span class="k">let</span> exclaimed <span class="p">=</span> map<span class="p">(</span>greetings<span class="p">,</span> <span class="p">{</span>key<span class="p">,</span> val <span class="p">-&gt;</span> Exclaim<span class="p">(</span>val<span class="p">)})</span>
echo exclaimed
<span class="c">" ['Hey!', 'Howdy!', 'Hi!']</span>
</code></pre></div></div>
<p>We can even remove our simple function entirely and perform our string modifications within the Lambda if we want:</p>
<div class="language-viml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">let</span> greetings <span class="p">=</span> <span class="p">[</span><span class="s1">'Hey'</span><span class="p">,</span> <span class="s1">'Howdy'</span><span class="p">,</span> <span class="s1">'Hi'</span><span class="p">]</span>
<span class="k">let</span> exclaimed <span class="p">=</span> map<span class="p">(</span>greetings<span class="p">,</span> <span class="p">{</span>key<span class="p">,</span> val <span class="p">-&gt;</span> val <span class="p">.</span> <span class="s1">'!'</span><span class="p">})</span>
echo exclaimed
<span class="c">" ['Hey!', 'Howdy!', 'Hi!']</span>
</code></pre></div></div>
<h1 id="thats-it">That’s it!</h1>
<p>There’s so much under the hood with VimL but effectively using functions is a great way to get started writing a simple script or plugin to help make your life better. I hope this helps remove some of the confusion that I initially had.</p>
Wed, 12 Jul 2017 00:00:00 +0000http://nick-tomlin.com/2017/07/12/viml-functions/
http://nick-tomlin.com/2017/07/12/viml-functions/JSX with Emmet Vim<blockquote>
<p>Apparently I’m very bad about writing blog posts; I’m going to try and do more bite sized “tactical” updates like this and see how it goes</p>
</blockquote>
<p>I’ve used the excellent <a href="https://github.com/mattn/emmet-vim">emmet.vim</a> for quite some time but had never gotten around to fixing some pesky annoyances when dealing with JSX: the default <code class="highlighter-rouge">class</code> won’t work with JSX and that double quoted attributes are pure evil. After perusing <a href="https://github.com/mattn/emmet-vim/issues/255">this emmet vim issue</a> (from 2015! I’m way behind the times!) and trying one of the many solutions thrown out in the thread, I found the following configuration for Emmet Vim suited my needs:</p>
<div class="language-viml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c">" .vimrc</span>
<span class="k">let</span> <span class="nv">g:user_emmet_settings</span> <span class="p">=</span> <span class="p">{</span>
<span class="se">\</span> <span class="s1">'javascript.jsx'</span> <span class="p">:</span> <span class="p">{</span>
<span class="se">\</span> <span class="s1">'extends'</span><span class="p">:</span> <span class="s1">'jsx'</span><span class="p">,</span>
<span class="se">\</span> <span class="s1">'quote_char'</span><span class="p">:</span> <span class="s2">"'"</span><span class="p">,</span>
<span class="se">\</span> <span class="p">},</span>
<span class="se">\</span><span class="p">}</span>
</code></pre></div></div>
<p>I am now happily Vimming away:</p>
<script type="text/javascript" src="https://asciinema.org/a/124232.js" id="asciicast-124232" async=""></script>
<p>Please share any tricks/tips for productive emmeting in the comments. Cheers!</p>
Sat, 10 Jun 2017 00:00:00 +0000http://nick-tomlin.com/2017/06/10/jsx-with-emmet-vim/
http://nick-tomlin.com/2017/06/10/jsx-with-emmet-vim/Hardcoded sub queries in Postgres<p>I recently ran into an issue where I needed to write an <code class="highlighter-rouge">IN</code> filter that consumed values from a sub query and hard-coded list. While I could express this relatively elegantly using an ORM to run the subquery and append the results to an array of hardcoded strings, I was struggling with how to do so raw SQL query.</p>
<p>My first attempt was to use <code class="highlighter-rouge">WITH</code> and a simple CTE:</p>
<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">WITH</span> <span class="n">hardcoded_user_ids</span><span class="p">(</span><span class="n">id</span><span class="p">)</span> <span class="k">as</span> <span class="p">(</span>
<span class="k">VALUES</span> <span class="p">(</span><span class="mi">1</span><span class="p">),</span> <span class="p">(</span><span class="mi">2</span><span class="p">)</span>
<span class="p">)</span>
<span class="k">SELECT</span> <span class="o">*</span> <span class="k">FROM</span> <span class="n">orders</span>
<span class="k">WHERE</span> <span class="n">orders</span><span class="p">.</span><span class="n">user_id</span> <span class="k">IN</span> <span class="p">(</span>
<span class="k">SELECT</span> <span class="n">id</span> <span class="k">from</span> <span class="n">normal_users</span>
<span class="k">UNION</span> <span class="k">ALL</span>
<span class="k">SELECT</span> <span class="n">id</span> <span class="k">FROM</span> <span class="n">hardcoded_user_ids</span>
<span class="p">);</span>
</code></pre></div></div>
<p>This was fine, but the CTE felt a bit verbose and unnecessary for my purposes. After some experimentation, I realized that this is possible using <code class="highlighter-rouge">AS</code> and specifying the column name:</p>
<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">SELECT</span> <span class="o">*</span> <span class="k">FROM</span> <span class="n">orders</span>
<span class="k">WHERE</span> <span class="n">orders</span><span class="p">.</span><span class="n">user_id</span> <span class="k">IN</span> <span class="p">(</span>
<span class="k">SELECT</span> <span class="n">id</span> <span class="k">FROM</span> <span class="n">normal_users</span>
<span class="k">UNION</span> <span class="k">ALL</span>
<span class="k">SELECT</span> <span class="n">id</span> <span class="k">from</span> <span class="p">(</span>
<span class="k">values</span> <span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="p">(</span><span class="mi">2</span><span class="p">)</span>
<span class="p">)</span> <span class="k">as</span> <span class="n">hardcoded_user_ids</span><span class="p">(</span><span class="n">id</span><span class="p">)</span>
<span class="p">)</span>
</code></pre></div></div>
<p>While the CTE route may actually be clearer in the long run, I like the formatting of the inline values list for simple one offs.</p>
Sun, 22 May 2016 00:00:00 +0000http://nick-tomlin.com/2016/05/22/hardcoded-subqueries-in-postgres/
http://nick-tomlin.com/2016/05/22/hardcoded-subqueries-in-postgres/sql,postgresSQL Goodies<p>I’ve recently been diving into SQL (<a href="http://www.postgresql.org/">postgres</a> to be exact). Here are a few random tidbits that have helped me on my journey.</p>
<h2 id="things-to-read">Things to read</h2>
<p><strong>Don’t read blogs</strong> (except mine 😉) While there are <em>many</em> helpful resources on the internet for learning about SQL, I’ve found the scattershot approach of reading blogs to be less than helpful in my own journey. They often cover only part of a subject or are too focused on a specific dialect to be truly helpful. I’m not suggesting that articles are never helpful, but that they can remove clarity when you are starting out. Longer form material is much better suited at the early stages.</p>
<p>To that end, I’ve found <a href="http://www.amazon.com/Learning-SQL-Alan-Beaulieu/dp/0596520832">Learning SQL</a> to be the best comprehensive guide on SQL; it includes a sample database and exercises with each chapter that provide a great way to exercise the concepts you read. There are plenty of long-form books out there, but this was the most approachable and comprehensive for basic concepts.</p>
<p>SQL Joins were an initially for me, but <a href="https://blog.codinghorror.com/a-visual-explanation-of-sql-joins/">A visual explanation of SQL joins</a> helped clear up the confusion. It is the best of <em>many many</em> posts about joins.</p>
<h2 id="things-to-do">Things to do</h2>
<p>Like many things, getting more comfortable with SQL is all about actually doing things with the language.</p>
<ul>
<li>Play around with <a href="http://sqlfiddle.com/">SQL fiddle</a> which is a great low-impact place to try out new ideas and concepts</li>
<li>Use simple CTE’s when you don’t want/need a schema
<ul>
<li>This is a great low overhead way of playing around with a small set of data without the need to declare a set schema or <code class="highlighter-rouge">insert</code> rows.</li>
<li>In Postgres, this can be accomplished using <code class="highlighter-rouge">with</code></li>
</ul>
</li>
</ul>
<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">-- postgres only, alas</span>
<span class="k">WITH</span>
<span class="n">characters</span> <span class="p">(</span><span class="n">id</span><span class="p">,</span> <span class="n">first_name</span><span class="p">,</span> <span class="n">last_name</span><span class="p">)</span> <span class="k">as</span> <span class="p">(</span>
<span class="k">VALUES</span>
<span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="s1">'Harry'</span><span class="p">,</span> <span class="s1">'Potter'</span><span class="p">),</span>
<span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="s1">'Ron'</span><span class="p">,</span> <span class="s1">'Weasley'</span><span class="p">)</span>
<span class="p">),</span>
<span class="n">wands</span> <span class="p">(</span><span class="n">id</span><span class="p">,</span> <span class="n">character_id</span><span class="p">,</span> <span class="n">name</span><span class="p">)</span> <span class="k">as</span> <span class="p">(</span>
<span class="k">VALUES</span>
<span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="s1">'Unicorn Core'</span><span class="p">),</span>
<span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="s1">'Maple Core'</span><span class="p">)</span>
<span class="p">)</span>
<span class="k">SELECT</span> <span class="n">name</span><span class="p">,</span> <span class="n">first_name</span><span class="p">,</span> <span class="n">last_name</span> <span class="k">from</span> <span class="n">wands</span>
<span class="k">INNER</span> <span class="k">JOIN</span> <span class="n">characters</span> <span class="k">ON</span> <span class="n">characters</span><span class="p">.</span><span class="n">id</span> <span class="o">=</span> <span class="n">wands</span><span class="p">.</span><span class="n">character_id</span><span class="p">;</span>
</code></pre></div></div>
<ul>
<li>Use a dataset that matters to you. If you workplace provides a sanitized read-only copy of data, use it! If that doesn’t spark your interest, create your own database (favorite sports tems, ninja clans, etc), or convert something from <a href="https://www.google.com/#q=open+data">data.gov</a> or other data providers). I find it much easier to work with data that I have an emotional or business connection to.</li>
</ul>
<h2 id="an-orm-should-be-a-jetpack-not-a-crutch">An ORM should be a jetpack, not a crutch</h2>
<p>ORMs like ActiveRecord are fantastic, they enable teams to write easy, reusable queries without littering your code with verbose SQL. Unfortunately, this means that when you need to dip down into raw SQL or troubleshoot a SQL problem, you can be left out in the cold.</p>
<p>Most ORMs provide a query logging feature, or a way to translate a series of method calls into an SQL statement. In active record, this is the <code class="highlighter-rouge">to_sql</code> method, e.g. <code class="highlighter-rouge">MyModel.joins(:my_association).where(query: true).to_sql</code>. Using this can help you understand and translate complicated ORM logic into SQL to better understand what is going on under the hood.</p>
<p>Ensure that you understand the structure of your database by looking at it in a console (or a schema file, if your ORM provides one). Even if you are using an ORM, this will make the connections between objects much easier to visualize. It also helps demystify abstract and potentially confusing ORM concepts like <a href="http://guides.rubyonrails.org/association_basics.html#polymorphic-associations">PolyMorphic Associaitons</a> when you see what they are doing under the hood.</p>
<p>Once you have a feel for the structure of a database, use toy projects or a throwaway branch to selectively replace ORM code with raw SQL. Many ORMs will give you an ability to mix raw SQL in with their own wrappers. E.g. ActiveRecord will allow you to <code class="highlighter-rouge">select</code> off of queries, or execute a raw sql statement with <code class="highlighter-rouge">ActiveRecord.base.connection.execute</code>. This provides a great way to gradually start using SQL without jumping in head first (if that’s not your cup of tea). It’s also a great way to see how an ORM may optimize (or <em>not</em> optimize) your queries.</p>
<p>The more you learn about SQL (and how your ORM formats SQL) the better your code (whether raw or ormified) will be.</p>
<h2 id="console-tips">Console tips</h2>
<p>The SQL console is one of the most useful tools for learning SQL and discovering your dataset. Here are a few tricks and tips</p>
<ul>
<li><code class="highlighter-rouge">explain</code> to see what your queries are doing under the hood</li>
<li><code class="highlighter-rouge">show tables</code> (or <code class="highlighter-rouge">\d</code> for Postgres) gives you your DB’s structure</li>
<li><code class="highlighter-rouge">describe &lt;table&gt;</code> (or <code class="highlighter-rouge">\d &lt;table&gt;</code> for PG) gives you a table’s structure</li>
<li><code class="highlighter-rouge">\e</code> in a console will open the current command in the editor of your choice. Very handy for tweaking long queries</li>
</ul>
<p><strong>Postgres Only</strong></p>
<ul>
<li><code class="highlighter-rouge">\x</code> Use super pretty “extended display” for outputting queries</li>
<li><code class="highlighter-rouge">\i file.sql</code> (PG only) executes a query from a file</li>
<li><code class="highlighter-rouge">\o output.out</code> writes output to <code class="highlighter-rouge">output.out</code> which can be great for storing the results of a query for later</li>
</ul>
Wed, 18 May 2016 00:00:00 +0000http://nick-tomlin.com/2016/05/18/sql-goodies/
http://nick-tomlin.com/2016/05/18/sql-goodies/sql,postgresProgrammatically running npm scripts<p>npm has become an essential part of my tool-chain, and I often use the <code class="highlighter-rouge">scripts</code> entry in lieu of build tools like Gulp or Grunt for small to medium sized projects. One issue that I’ve encountered is wanting to kick off tasks stored in the <code class="highlighter-rouge">scripts</code> without actually running <code class="highlighter-rouge">npm</code> on the shell. Googling did not lead to any easy answers, but the solution was readily apparent from the <code class="highlighter-rouge">npm-cli</code> <a href="https://github.com/npm/npm/blob/master/bin/npm-cli.js#L69">source</a>.</p>
<p>Once you have installed npm locally <code class="highlighter-rouge">npm i npm --save</code> [insert “Yo dawg…” reference here], you can require and use it:</p>
<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">var</span> <span class="nx">npm</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="s1">'npm'</span><span class="p">);</span>
<span class="nx">npm</span><span class="p">.</span><span class="nx">load</span><span class="p">({},</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">er</span><span class="p">)</span> <span class="p">{</span>
<span class="k">if</span> <span class="p">(</span><span class="nx">er</span><span class="p">)</span> <span class="p">{</span> <span class="k">return</span><span class="p">;</span> <span class="p">}</span>
<span class="nx">npm</span><span class="p">.</span><span class="nx">commands</span><span class="p">.</span><span class="nx">run</span><span class="p">([</span><span class="s1">'test'</span><span class="p">]);</span>
<span class="p">});</span>
</code></pre></div></div>
<p>This is obviously a very simplistic use case, but hopefully it provides some food for thought. Let me know if you are able to build something interesting with it.</p>
<h1 id="edit">Edit</h1>
<p>In the comments, @bfredit noted that you can use the <a href="https://www.npmjs.com/package/global-npm"><code class="highlighter-rouge">global-npm</code></a> module to avoid bringing the hefty <code class="highlighter-rouge">npm</code> package locally.</p>
Fri, 04 Sep 2015 17:32:00 +0000http://nick-tomlin.com/2015/09/04/programmatically-running-npm-scripts/
http://nick-tomlin.com/2015/09/04/programmatically-running-npm-scripts/npmnodeUsing stackoverflow as a learning tool<p>I first experienced the magic of Google when I was trapped on the 2nd puzzle in <a href="http://en.wikipedia.org/wiki/Myst">Myst</a>: a few quick keyboard strokes and I had the solution to that damnable clock puzzle that thwarted me for hours. My nine year old self was astounded that someone out there had an answer to the exact question I typed in. The only thing that recaptures the magic for me is <a href="http://stackoverflow.com/">StackOverflow</a>.</p>
<p>While it primarily serves as a knowledge base — one of the best if not <em>the</em> best — StackOverflow can also be used as a powerful tool in the apprentice developer’s kit. Taking a cue from the invaluable <a href="http://apprenticeship-patterns.labs.oreilly.com/">Apprenticeship Patterns</a>, i’ve developed a few patterns of my own that I use to get the most out of Stack Overflow:</p>
<h2 id="1-flashcards">1. Flashcards</h2>
<p>I’ve always found flashcards and quizzes to be the most helfpul ways to retain things. When I was studying language in Primary school, I always made it a point to have a friend (or my mom, thanks mom!) quiz me on a list of topics or vocabulary words. This practice of quizzing allowed me to rediscover words/topics that had fallen out of my memory, and get a better understanding on ones I already knew. I use SO in a simlar way.</p>
<ol>
<li>Look for low to no answer questions in the discipline you are interested (<code class="highlighter-rouge">node.js</code> for example).</li>
<li>give the question a quick scan, to see if you know the answer</li>
<li>if so, give a clear and concise answer. Otherwise, make a note of the question for later, and then go back to step 1.</li>
</ol>
<p>The key here is to not get bogged down researching the answer to a question that is beyond your quick-acccess memory (thats for the next pattern). I find this much more stimulating than making my own flashcards, and the variety of questions help me look at what I know from a different perspective, or reveal holes in my own knowledge. Keeping a log of questions that I do not know gives me research projects for later.</p>
<h2 id="2-deep-dive">2. Deep Dive</h2>
<p>There are a lot of questions on SO (usually by inexperienced users) that can be solved with a simple google search, or a cursory examination of documentation. It’s easy to pick up some quick reputation points by answering these — i’ve definetely done so — but it’s easy to fall prey to using surface level knowledge instead of deepening your understanding of a topic.</p>
<p>To get around this, I will set aside certain times where I only answer questions by referring to the source code of the technology in question. This forces me to really understand the fundamentals at play in solving the question. Often, I won’t be able to figure out what is going on in time to get the right answer (or maybe at all), but the end result is that I gain a much much better understanding of how the technology functions, and a better grasp of how to read code. If I do happen to get the right answer, it’s all the more rewarding.</p>
<h2 id="3-reduce-reuse-recycle">3. Reduce, Reuse, Recycle</h2>
<p>SO has a wealth of “canonized” questions and answers, and i’ve found it helpful to keep a list of the ones that I find the most helpful. Combining and reviewing these has allowed me to get a much better handle on complex concepts like OO, Prototypical Inheritance in JS, and what the hell MVC is.</p>
<p>I’ve found it helpful to collect several similar answers in a blog post or entry in my private wiki. This creates a rich “super answer”, and the act of synthesizing helps me better understand the topic.</p>
<p>A second benefit of these “canonized” answers is battle bewtween various schools of thought on what the best way to solve a problem really is. Being able to see one of the creators of Python argue with another advanced user over the performance of Arrays is a wonderful gift to an apprentice programmer. I’ve found it useful to mark these answers, and then explore the reasoning behind each one.</p>
<h2 id="onward-and-upward">Onward and Upward</h2>
<p>StackOverflow has aided me incredibly, and I hope some of these patterns can help you as well. If you have any thoughts, <a href="twitter.com/itsnicktomlin">@mention me</a> or leave a comment.</p>
Mon, 01 Jul 2013 20:45:00 +0000http://nick-tomlin.com/2013/07/01/stackoverflow-as-a-learning-tool/
http://nick-tomlin.com/2013/07/01/stackoverflow-as-a-learning-tool/Replacing Common Photoshop workflows with ImageMagick<p>Photoshop is a wonderful tool, but it tends to require mousing (even with shortcuts), likes to eat up as much RAM as possible, and doesn’t play nice with bash scripts. Thats why I prefer <a href="http://www.imagemagick.org/script/index.php">Image Magick</a>: a quirky, insanely full-featured CLI image manipulation library. I’ll run through some examples of using it do a few common tasks that I previously used photoshop for, such as:</p>
<ul>
<li>Identify the size/type of image</li>
<li>Convert image types</li>
<li>Resize images to a maximum width/height</li>
<li>Reduce image filesize</li>
<li>Trim Whitespace</li>
<li>Create new images from scratch</li>
<li>Add borders</li>
</ul>
<p><strong>Example Repository</strong></p>
<p>If you want to follow along, i’ve created an <a href="https://bitbucket.org/nicktomlin/imagemagick-examples/">example repository</a> with some source files. I’ll be referencing them through the post.</p>
<h2 id="installation">Installation</h2>
<h3 id="mac-os-x">Mac Os X</h3>
<p>Mac users can (and should) use <a href="http://mxcl.github.com/homebrew/">brew</a> :</p>
<p><code class="highlighter-rouge">
brew install imagemagick
</code></p>
<h3 id="linux">Linux</h3>
<p>Most linux distributions should have the <code class="highlighter-rouge">imagemagick</code> package available by default.</p>
<p>For Ubuntu:</p>
<p><code class="highlighter-rouge">apt-get install imagemagick</code></p>
<h2 id="there-be-dragons-mogrify-vs-convert">There be dragons: Mogrify Vs. Convert</h2>
<p>One important thing to cover before we start slicing and dicing images is that IM has two major methods for manipulating images: <code class="highlighter-rouge">convert</code> and <code class="highlighter-rouge">mogrify</code>. <code class="highlighter-rouge">Convert</code> takes a source file, makes whatever changes you desire to it and ouptus them to a file you specify. <code class="highlighter-rouge">Mogrify</code> only accepts one file, and makes all changes on that file (unless you specify a destination directory). <code class="highlighter-rouge">mogrify</code> has a simpler syntax for performing batch operations on images, but that elegance comes with the potential of deleting precious content. There’s an example of how to handle batch operations using both commands in the “resize” section later on. For now, just be warned that <code class="highlighter-rouge">mogrify</code> will write any changes you make to the <strong>original</strong> files. Back up early; back up often.</p>
<h2 id="identify-the-size-and-type-of-images"><a href="http://www.imagemagick.org/script/command-line-options.php#identify">Identify</a> the size and type of images</h2>
<p><code class="highlighter-rouge">identify</code> is great for getting a quick overview of an image’s properties.</p>
<table>
<tbody>
<tr>
<td>Our example’s source file includes an image file named <code class="highlighter-rouge">300</code>, which i’ve nabbed from <a href="http://placekitten.com/">PlaceKitten</a>. Photoshop doesn’t know what to do with the image, because it is missing an extension, and while we could try and guess the extension by renaming the file to (gif</td>
<td>png</td>
<td>jpg) and seeing what happens, but it’s cooler (and faster) to use the <code class="highlighter-rouge">identify</code> command to figure things out:</td>
</tr>
</tbody>
</table>
<div class="language-shell highlighter-rouge"><div class="highlight"><pre class="highlight"><code>identify 300
300 JPEG 200x200 200x200+0+0 8-bit sRGB 8KB 0.000u 0:00.009
</code></pre></div></div>
<p>Ah, a jpeg. I suspected it all along.</p>
<h3 id="formatting-identifys-output">Formatting identify’s output</h3>
<p>The default output of the <code class="highlighter-rouge">identify</code> command is a little verbose for my taste. We can trim it down by using IM built in <code class="highlighter-rouge">-format</code> <a href="http://www.imagemagick.org/script/escape.php">escapes</a></p>
<pre><code> # Print the name, and dimensions of the file named 300
identify -format "Name: %f Dimensions: %P Type: %m" 300 </code></pre>
<p>Batch identification is simple with your shell’s built in <a href="http://wiki.bash-hackers.org/syntax/expansion/globs">globbing</a>:</p>
<pre><code>
# '*' will get you more than you ask for, so it's best to narrow
# things down based on the file structure you are dealing with
identify *</code></pre>
<h2 id="convert-image-formats">Convert image formats</h2>
<p>Imagemagick’s powerhouse is the <a href="http://www.imagemagick.org/script/convert.php"><code class="highlighter-rouge">convert</code></a> command. You can use it to do almost anything you can imagine through some terrifyingly complex flags. We’ll try to keep things simple : )</p>
<h3 id="convert-from-tiff-to-jpg">Convert from <code class="highlighter-rouge">tiff</code> to <code class="highlighter-rouge">jpg</code></h3>
<p>Image magick can effortlessly convert images between various formats. A problem one of my coworkers ran into recently involved clients needing images in the <code class="highlighter-rouge">tiff</code> format. Photoshop can do batch operations, but the process is clunky, and — in my experience— unreliable.</p>
<h4 id="single-images">Single Images:</h4>
<ul>
<li><code class="highlighter-rouge">convert convert.tiff kitten.jpg</code> Simple, no?</li>
</ul>
<h4 id="multiple-images">Multiple Images:</h4>
<ul>
<li>destroying the original image:
<ul>
<li><code class="highlighter-rouge">mogrify</code> <code class="highlighter-rouge">mogrify --format tiff *.jpg</code></li>
</ul>
</li>
<li>retaining the original image, the <code class="highlighter-rouge">mogrify</code> command can be used with the <code class="highlighter-rouge">-path</code> flag
<ul>
<li><code class="highlighter-rouge">mogrify --format tiff -path converted *.jpg</code></li>
<li>The path (in this case the ‘converted’ directory) must exist, or IM will complain</li>
<li>Make sure that this path is different than the files you are using <code class="highlighter-rouge">mogrify</code> on, or they will be overwritten.</li>
</ul>
</li>
<li>retaining the original image, you can use a long<code class="highlighter-rouge">convert</code> statement (see batch resizing below).</li>
</ul>
<h2 id="resize-images">Resize images</h2>
<h3 id="simple-resize">Simple Resize</h3>
<p><code class="highlighter-rouge">convert kitten.jpg -resize 80% resized-kitten.jpg</code></p>
<h3 id="batch-resizing">Batch Resizing</h3>
<p>Clients rarely have a images in a uniform, web-optimized format, and even if they do I usually need need two copies: retina-ready images, and images for us normal folks. ImageMagick makes generating those a snap.</p>
<p>In our <code class="highlighter-rouge">resize/batch</code> folder:</p>
<p><code class="highlighter-rouge">convert *.jpg -resize 80% -set filename:f '%t@2x' '%[filename:f].jpg'</code></p>
<p>Here we are resizing all jpg images by 80%, setting the filename the filename <code class="highlighter-rouge">%t</code> plus the string <code class="highlighter-rouge">@2x</code> to follow apple’s convention for retina images, and then outputting the file. The syntax is a little esoteric (more details on that <a href="http://www.imagemagick.org/Usage/files/#save_escapes">here</a>), but once you get the hang of it it can be quite useful.</p>
<p>We can now run <code class="highlighter-rouge">mogrify !(*@2x).jpg -resize 40%</code> to cut the non retina images down to size (note, this will “destroy” the original images – I have a backup handy).</p>
<h3 id="resizing-to-a-maximum-pixel-width">Resizing to a maximum pixel width</h3>
<p>If you have do not have a specific size for your images, but want to keep things small, you can use the following syntax:</p>
<p>In our <code class="highlighter-rouge">resize</code> folder, there is a max width image. Running identify gives us the following:</p>
<p><code class="highlighter-rouge">max-width.jpg JPEG 408x287 408x287+0+0 8-bit sRGB 15.8KB 0.000u 0:00.000</code></p>
<p>Let’s resize that to a max width of 200px:</p>
<p><code class="highlighter-rouge">convert max-width.jpg -resize 200\&gt; max-width-resized.jpg</code></p>
<p>One special thing to note is the icky need for the <code class="highlighter-rouge">\</code> in <code class="highlighter-rouge">\&gt;</code>. This is necessary to escape to prevent your shell from interpreting that as an output redirection <code class="highlighter-rouge">&gt;</code>.</p>
<h3 id="replacing-save-for-web-and-reducing-file-size-with--strip">Replacing “save-for-web” and reducing file size with <code class="highlighter-rouge">-strip</code></h3>
<p>When resizing images (especially large images), you may notice that the file size of the images does not decrease as much as you might expect. This is typically due the meta-data and other kruft that may come attached to your image file. Using the <code class="highlighter-rouge">-strip</code> flag on any IM operation will remove this data, which, in my experience, typically results in a 10-30% reduction in size.</p>
<p>In our <code class="highlighter-rouge">trim</code> folder:
<code class="highlighter-rouge">convert -strip strip.jpg stripped.jpg</code></p>
<p>Use <code class="highlighter-rouge">identify</code> to compare the file sizes. Not a huge reduction (this image is pretty slim already), but imagine those percentage savings being applied to a larger image.</p>
<p>Obviously, Photoshop’s “Save for web” combines resizing and optimizing functions, but you can too.</p>
<div class="highlighter-rouge"><div class="highlight"><pre class="highlight"><code>convert sample.png -strip -resize 80% optimized.png
</code></pre></div></div>
<h2 id="borders">Borders</h2>
<p>Add a 5px black border to an image.</p>
<p>In our <code class="highlighter-rouge">borders</code> folder:</p>
<p><code class="highlighter-rouge">convert kitten.jpg -bordercolor '#000' -border 5 bordered.jpg</code></p>
<h2 id="trim-whitespace">Trim Whitespace</h2>
<p>My jaw dropped when I first found out about this command (thanks to <a href="http://hilbertastronaut.blogspot.com/2008/08/imagemagick-crops-your-white-space.html">this</a> brilliant gentleman)</p>
<p>In our <code class="highlighter-rouge">trim-whitespace</code> folder</p>
<p><code class="highlighter-rouge">convert trim.png -trim trimmed.png</code></p>
<p>Unfortunately, for images with gradients, or subtle transitions between subject/background, the results are not quite as spectacular:</p>
<p><code class="highlighter-rouge">convert not-quite-trim.jpg -trim not-quite-trimmed.jpg</code></p>
<p>Will output an image that still has a background bleed :(</p>
<h2 id="create-images-from-the-command-line">Create Images from the command line</h2>
<p>Imagemagick can also help you with bespoke iamges as well, if you need some filler content and can’t use a service like placehold.it or (my favorite) placekitten.com.</p>
<p>To create a simple gray (usinga hex value), sized 100x100 you can use the convert command.</p>
<ul>
<li>
<p>Solid Color:
<code class="highlighter-rouge">convert -size 100x100 canvas:#a19c9e canvas.png</code>
(note, you may need to quote/escape hex colors, as your shell may try glob them)</p>
</li>
<li>
<p>Gradient:
<code class="highlighter-rouge">convert -size 100x100 gradient:#a19c9e-#000000 canvas.png</code></p>
</li>
<li>
<p>Pattern:
<code class="highlighter-rouge">convert -size 100x100 pattern:HEXAGONS canvas.png</code></p>
</li>
</ul>
<p>There are a host of options <a href="http://www.imagemagick.org/script/formats.php">here</a></p>
<h2 id="the-start-of-a-beautiful-friendship">The start of a beautiful friendship</h2>
<p>Hopefully these examples have whet your appetite for handling images on the command line. IM can do so so much more, and all those features are listed in
IM’s <a href="http://www.imagemagick.org/script/command-line-processing.php#sequence">extensive documentation</a>.</p>
<h2 id="notes">Notes</h2>
<h3 id="os-x-users-sips">Os X Users: <code class="highlighter-rouge">sips</code></h3>
<p>If you don’t want to bother installing IM, or you are on a friend’s Macbook and can’t. Use the built-in utility <code class="highlighter-rouge">sips</code> to do some batch image processing. While not as robust as ImageMagick, it suffice in a pinch. More on that <a href="https://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man1/sips.1.html">here</a>.</p>
<h3 id="im-and-build-processes">IM and Build Processes</h3>
<p>While IM is an excellent choice for performing large batch operations on images, it has been my experience that it is better suited for one off batch jobs than a constant build/deploy process. I’d suggest using tools like the <a href="https://github.com/h5bp/ant-build-script">HTML5 BoilerPlate Build script</a> or <a href="http://gruntjs.com/">Grunt</a> with the <a href="https://github.com/gruntjs/grunt-contrib-imagemin">grunt-contrib-imgmin</a> plugin on projects that may need to consistently run and rerun optimization.</p>
<h3 id="a-note-on-performance">A note on Performance</h3>
<p>ImageMagick has a more performant fork <a href="http://www.graphicsmagick.org/benchmarks.html">GraphicsMagick</a> if you are concerned about keeping resource usage down or if you are <a href="http://codeascraft.etsy.com/2010/07/09/batch-processing-millions-of-images/">etsy</a>. Most of the commands are similar, but the differences between the command structure and GM’s elusive api documentation make starting with imageMagick a better fit. You can always move on to GM when performance becomes a concern.</p>
<h2 id="corrections">Corrections</h2>
<p>If you are a command-line master, and i’ve missed something or missed a performant shortcut, don’t hesitate to note it in the comments. Or open an <a href="https://bitbucket.org/nicktomlin/imagemagick-examples/issues?status=new&amp;status=open">issue</a></p>
Sat, 16 Mar 2013 17:00:00 +0000http://nick-tomlin.com/2013/03/16/replacing-common-photoshop-workflows-with-imagemagick/
http://nick-tomlin.com/2013/03/16/replacing-common-photoshop-workflows-with-imagemagick/Let's Send an Html Email Using PHPmailer<p>I recently needed to send a create a form that would send an html email with a PDF attachement. Due to some project constraints, using a service like MailChimp (which I do love oh so much) was out of the question, so I had to work a little magic of my own. Let&#8217;s go on a little journey, shall we?</p>
<h2>Email: code like it&#8217;s 1999</h2>
<p>Email is still an anomly when it comes to web standards, where the old school way of doing thing still reigns. Be not afraid, however, because are a few tools that make things quite a bit easier.</p>
<h3>For starters: HTML Boilerplate</h3>
<p>There are a lot of quirks in email markup, and the <a href="http://htmlemailboilerplate.com/">HTML Email Boilerplate</a> does a great job of setting things up. You get tweaks for the various mail cients, a style reset, and a very basic markup template.</p>
<h3>The good stuff: your design</h3>
<p>Enjoy implementing your snazzy design here, but be sure to stay within the recommended 550-650px width (Mailchimp recommends 600px, so i&#8217;d say that&#8217;s a safe bet).</p>
<p>Feel free to write you styles in the <code>&lt;style&gt;&lt;/style&gt;</code> to make things easier as you design. We&#8217;ll use Premailer later on to move them inline.</p>
<p>Images can be hosted on your website, a CDN, or you can attach them to the email with PHPmailer.</p>
<h3>Finishing things off: Premailer</h3>
<p>Now that we have our beautiful template all tabled up and ready, we want to make sure it plays nicely with as many email clients as possible. The best way that i&#8217;ve found is to use <a href="http://premailer.dialect.ca">Premailer</a>. Premailer will take your lovely html template, work some magic on it, and give you a leaner, friendler version that even picky clients like outlook (and, suprisingly, gmail) will love.</p>
<p>Save the premailer formatted html to a file in your project directory (we&#8217;ll need to reference it in our PHP script later on).</p>
<h2>Let&#8217;s Send this puppy!</h2>
<p>We are so close, but&#8230; now we actually have to send the thing. Easier said than done.</p>
<h3>MIMEs are a pain</h3>
<p>The first hurdle is getting the proper MIME headers for the various elements of our email.
We could just use PHP&#8217;s built in mail() and write our own MIME headers for all the content (which supposes that you know enough to write your own MIME headers &#8211; I don&#8217;t), but let&#8217;s take a look at how much fun that is:</p>
<figure class="code"><div class="highlight"><table><td class="gutter"><pre class="line-numbers"><span class="line-number">1</span>
<span class="line-number">2</span>
</pre></td><td class="code"><pre><code class="plain"><span class="line">$body .="Content-Type: text/html; charset=\"iso-8859-1\"";
</span><span class="line">$body .= "Content-Transfer-Encoding: 8bit";</span></code></pre></td>&lt;/tr&gt;</table></div></figure>
<p>Now imagine having to set that for your attachments (which you need to open and encode properly), the html email file, and the plain text version of your email. If you get things wrong, it&#8217;s up to you to figure out the esoteric error messages of mail() and various email clients. Whooo&#8230; no thanks. That&#8217;s why we&#8217;ll use PHPmailer to do it for us.</p>
<h3>PHPMailer to the rescue</h3>
<p><a href="http://code.google.com/a/apache-extras.org/p/phpmailer/">PHPMailer</a> is an apache extra that takes a lot of the confusion out of sending emails. Just download it to your project directory, include it in your PHP file and follow the tutorial <a href="http://code.google.com/a/apache-extras.org/p/phpmailer/wiki/UsefulTutorial">here</a> or modify my script below:</p>
<div class="language-php highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">require_once</span><span class="p">(</span><span class="nx">includes</span><span class="o">/</span><span class="nx">phpmail</span><span class="o">.</span><span class="k">class</span><span class="err">)</span> <span class="err">//</span> <span class="nc">or</span> <span class="nx">wherever</span> <span class="nx">you</span> <span class="nx">put</span> <span class="nx">phpmail</span><span class="o">.</span><span class="k">class</span>
<span class="nc">body</span> <span class="o">=</span> <span class="nb">file_get_contents</span><span class="p">(</span><span class="s1">'email/htmlemail.html'</span><span class="p">);</span> <span class="c1">// include our formatted email
</span>
<span class="nv">$mail</span><span class="o">-&gt;</span><span class="na">AltBody</span> <span class="o">=</span> <span class="s2">"To view this message please use an HTML compatible email viewer, or visit http://mysite.com/emailcampaign"</span><span class="p">;</span> <span class="c1">// give folks who can't read HTML email something to read
</span><span class="nv">$mail</span><span class="o">-&gt;</span><span class="na">SetFrom</span><span class="p">(</span><span class="nv">$email</span><span class="p">,</span><span class="nv">$name</span><span class="p">);</span>
<span class="nv">$address</span> <span class="o">=</span> <span class="nv">$email</span><span class="p">;</span>
<span class="nv">$mail</span><span class="o">-&gt;</span><span class="na">AddAddress</span><span class="p">(</span><span class="nv">$address</span><span class="p">,</span> <span class="nv">$name</span><span class="p">);</span>
<span class="nv">$mail</span><span class="o">-&gt;</span><span class="na">Subject</span> <span class="o">=</span> <span class="s2">"Subject"</span><span class="p">;</span>
<span class="nv">$mail</span><span class="o">-&gt;</span><span class="na">MsgHTML</span><span class="p">(</span><span class="nv">$body</span><span class="p">);</span>
<span class="nv">$mail</span><span class="o">-&gt;</span><span class="na">addAttachment</span><span class="p">(</span><span class="s2">"email/attachment.pdf"</span><span class="p">);</span> <span class="c1">// just repeat this for multiple attachments
</span>
<span class="c1">// send statement, followed by error reporting (comment out for production)
</span><span class="k">if</span><span class="p">(</span><span class="o">!</span><span class="nv">$mail</span><span class="o">-&gt;</span><span class="na">Send</span><span class="p">())</span> <span class="p">{</span>
<span class="k">echo</span> <span class="s2">"Mailer Error: "</span> <span class="o">.</span> <span class="nv">$mail</span><span class="o">-&gt;</span><span class="na">ErrorInfo</span><span class="p">;</span> <span class="c1">// for testing
</span><span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
<span class="k">echo</span> <span class="s1">'Message sent!'</span><span class="p">;</span> <span class="c1">// for testing
</span><span class="p">}</span>
</code></pre></div></div>
<h2>The end.</h2>
<p>And there we have it, a functional workflow for an html email with some killer attachments. It&#8217;s not perfect by any means, but it has made things a lot less easier for me. Suggestions for improvement are more than welcome, just shoot me a comment.</p>
<p>Happy Emailing,<br />
Nick</p>
Fri, 31 Aug 2012 16:25:00 +0000http://nick-tomlin.com/2012/08/31/using-phpmailer-for-fun-and-profit/
http://nick-tomlin.com/2012/08/31/using-phpmailer-for-fun-and-profit/phphtml emailA command line manifesto<p><small>Note:
I will be using “terminal” and “the command line” interchangeably. If there’s better language to use, drop me a comment and I will change things around.
</small></p>
<p>My first experience with the command line was trying to play Wolfenstein 3D in windows 3.1. It was off-putting, a little scary, and I viewed the experience as a painful – but necessary – hurdle on the road to fun. From conversations i’ve had with others, this is not an uncommon perspective on terminal in the front-end community.</p>
<p>I felt the same until my stint as the IT admin/developer/sysadmin for a non-profit. I found myself developing on several servers of varying Linux flavors and, since some of these boxes were headless, I found myself having to break open the command line. My initial reaction to doing everything on the command line was terror but now, I try to do as much as I can on the command line.</p>
<p>Here’s why:</p>
<h3 id="speed">Speed</h3>
<p>Things are just faster on the command line.
Consider the following:</p>
<h4 id="workflow-installing-wordpress">Workflow: Installing wordpress</h4>
<h5 id="gui">GUI</h5>
<ol>
<li>Download www.wordpress.org/latest.zip in your browser</li>
<li>Find and unzip the files on your local machine</li>
<li>Log into your site via FTP</li>
<li>Upload the files via FTP</li>
<li>Make a sandwich</li>
<li>Run setup</li>
</ol>
<h5 id="command-line-via-ssh">Command Line (via ssh)</h5>
<div class="language-shell highlighter-rouge"><div class="highlight"><pre class="highlight"><code>wget www.wordpress.org/latest.zip
unzip latest.zip
<span class="c"># run setup / or nano config file</span>
</code></pre></div></div>
<p>Not only does the command line version get things done 2 lines (possibly one, if you have more command-fu than I do), but it does also it significantly faster by removing the local machine from the process. Waiting for 500+ files to transfer one by one via FTP is no fun.</p>
<p>Things are even better for Drupal, using <a href="http://drupal.org/project/drush/">drush</a>, but I won’t go into detail about that here.</p>
<h3 id="simplicity">Simplicity</h3>
<p>I work in Mac Os X, which is based on Unix, and all of the sites work in a LAMP (Linux/apache/mysql/php) environment, so I find it pretty natural moving between the server and my local machine. This means tricks I pick up locally work remotely, and vice versa.</p>
<p>In addition, It’s quite helpful to be familiar with the environment where the things I make are going to live. If something doesn’t go according to plan on the server, I know some basic things to try, and I can give a lot more informed report to my sysadmin if I need help.</p>
<p>Finally, if you use SASS, LESS, or GIT you can run those from terminal without having to buy a gui app (however <a href="http://incident57.com/codekit/">nice</a>). All those new tools fit harmoniously into the same environment you are used to without any added overhead/app funkiness.</p>
<h3 id="extensibility">Extensibility</h3>
<p>One of my initial frustrations with working on the command line was the sheer amount of time it took to get around. The shortcuts that i’d relied on (liking dragging a folder into “favorites”) were gone. While customizing things is not the most intuitive process initially, you really can have things formatted however you like, and do some crazy stuff you could never do with a GUI. I’d never go back now, simply because I wouldn’t have the same options that I do on the command line.</p>
<p>A few customizations i’ve found helpful:</p>
<ol>
<li>
<p>Open files in Photoshop</p>
<p>I created a <code class="highlighter-rouge">shop</code> alias, so I don’t have to leave the command line and hunt through finder. For example, I can open all the transparent .png files for my home page with: <code class="highlighter-rouge">shop images/home-*.png</code></p>
</li>
<li>
<p>Open files in my text editor from the command line</p>
<p>A simple <code class="highlighter-rouge">subl .</code> and an entire directory opens up as a project, or <code class="highlighter-rouge">subl *.php</code> and i’ve opened all php files.</p>
</li>
<li>
<p>Use <a href="http://www.huyng.com/projects/bashmarks/">bashmarks</a> to get around <em>fast</em></p>
<p>I use <code class="highlighter-rouge">s sites</code> to book mark my sites directory. Then, <code class="highlighter-rouge">g sites</code> gets me back.</p>
</li>
</ol>
<p>This is just scratching the surface of what you can do; these were all simple to set up and I use most of them everyday. Pretty fantastic if you find yourself repeating some common tasks.</p>
<h2 id="no-pressure">No pressure</h2>
<p>All that said, the beauty of the command line is that you can use as much or as little as you want. If you find that it saves you time to deploy via the command line, but you prefer to do everything else via a GUI, then that’s more than fine. I think the most important thing is to not be afraid of the command line – or at least know what you are afraid of. I still do a lot of things the “old fashioned” way, but I have found the command line to be a helpful addition to my toolkit. Hopefully it will do the same for you : )</p>
<p>Happy coding,
Nick</p>
Fri, 10 Aug 2012 16:41:00 +0000http://nick-tomlin.com/2012/08/10/a-command-line-manifesto/
http://nick-tomlin.com/2012/08/10/a-command-line-manifesto/Terminal