<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
  <id>http://arjanvandergaag.nl/</id>
  <title>arjanvandergaag.nl</title>
  <updated>2013-03-02T13:00:00Z</updated>
  <link rel="alternate" href="http://arjanvandergaag.nl/"/>
  <link rel="self" href="http://arjanvandergaag.nl/feed.xml"/>
  <author>
    <name>Arjan van der Gaag</name>
    <uri>http://arjanvnadergaag.nl</uri>
  </author>
  <entry>
    <id>tag:arjanvandergaag.nl,2013-03-02:/blog/working-with-postgresql-on-the-command-line.html</id>
    <title type="html">Working with Postgresql on the command line</title>
    <published>2013-03-02T13:00:00Z</published>
    <updated>2013-03-02T13:00:00Z</updated>
    <link rel="alternate" href="http://arjanvandergaag.nl/blog/working-with-postgresql-on-the-command-line.html"/>
    <content type="html">&lt;p class="leader"&gt;Unlike My&lt;span class="caps"&gt;SQL&lt;/span&gt;, Postgre&lt;span class="caps"&gt;SQL&lt;/span&gt; doesn’t have lots of nice-looking &lt;span class="caps"&gt;GUI&lt;/span&gt; tools&amp;nbsp;available
to it. But don’t let that hold you back, because its command-line client packs&amp;nbsp;a
lot of power that you’ll quickly come to love, once you get to know&amp;nbsp;it.&lt;/p&gt;

&lt;h2&gt;Editing your&amp;nbsp;queries&lt;/h2&gt;

&lt;p&gt;You can use the &lt;code&gt;psql&lt;/code&gt; program to interactively send queries to your&amp;nbsp;database.
Although there are steps you can take to make editing in the interactive&amp;nbsp;shell
easier&lt;sup id="fnref:1"&gt;&lt;a href="#fn:1" rel="footnote"&gt;1&lt;/a&gt;&lt;/sup&gt;, nothing beats your regular&amp;nbsp;editor.&lt;/p&gt;

&lt;p&gt;To create a new &lt;span class="caps"&gt;SQL&lt;/span&gt; file in your editor and quickly send it to your&amp;nbsp;database,
you can use the &lt;code&gt;--file&lt;/code&gt; (or &lt;code&gt;-f&lt;/code&gt;) option. Assuming you use Vim, here are&amp;nbsp;two
example key&amp;nbsp;mappings:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;map &amp;lt;leader&amp;gt;r :w !psql -d mydb -1 -f -&amp;lt;cr&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This allows you to use &lt;code&gt;\r&lt;/code&gt; in normal mode to execute the entire file, or&amp;nbsp;in
visual mode to execute only the current selection. Note the use of the&amp;nbsp;&lt;code&gt;-1&lt;/code&gt;
option (short for &lt;code&gt;--single-transaction&lt;/code&gt;) to wrap your queries in a&amp;nbsp;transaction,
as if you had used &lt;code&gt;BEGIN&lt;/code&gt;/&lt;code&gt;COMMIT&lt;/code&gt;, and the &lt;code&gt;-&lt;/code&gt; argument to &lt;code&gt;-f&lt;/code&gt; to tell&amp;nbsp;&lt;code&gt;psql&lt;/code&gt;
to read from standard&amp;nbsp;input.&lt;/p&gt;

&lt;p&gt;Alternatively, you can start your editor &lt;em&gt;from&lt;/em&gt; the &lt;code&gt;psql&lt;/code&gt; prompt using&amp;nbsp;the
&lt;code&gt;\edit&lt;/code&gt; (or &lt;code&gt;\e&lt;/code&gt;) metacommand. This will launch &lt;code&gt;$EDITOR&lt;/code&gt; to edit a&amp;nbsp;temporary
file containing the last query you ran. When you quit the editor, &lt;code&gt;psql&lt;/code&gt;&amp;nbsp;will
run the contents of that file as the next&amp;nbsp;query.&lt;/p&gt;

&lt;p&gt;Finally, you can use Postgre&lt;span class="caps"&gt;SQL&lt;/span&gt; variables and interpolation to make&amp;nbsp;writing
queries a little easier. For&amp;nbsp;example:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;psql&amp;gt; \set t my_long_table_name
psql&amp;gt; select count(*) from :t;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Note how &lt;code&gt;psql&lt;/code&gt; will interpolate &lt;code&gt;:t&lt;/code&gt; with &lt;code&gt;my_long_table_name&lt;/code&gt;. You might&amp;nbsp;use
this to read a blob of data from a file, and insert it into a&amp;nbsp;row:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;psql&amp;gt; \set content `cat my_big_textfile`
psql&amp;gt; INSERT INTO posts VALUES (:'content');
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The quotes in the placeholder name will escape the variable contents as an &lt;span class="caps"&gt;SQL&lt;/span&gt;&amp;nbsp;literal.&lt;/p&gt;

&lt;h2&gt;Inspecting&amp;nbsp;tables&lt;/h2&gt;

&lt;p&gt;The main reason I used to prefer GUIs to work with databases is how easy&amp;nbsp;they
make it explore the database schema. &lt;code&gt;psql&lt;/code&gt; provides a handy family&amp;nbsp;of
metacommands to explore objects in the database, all starting with &lt;code&gt;\d&lt;/code&gt;.&lt;sup id="fnref:3"&gt;&lt;a href="#fn:3" rel="footnote"&gt;2&lt;/a&gt;&lt;/sup&gt; You
can list all tables in  your current schema using just &lt;code&gt;\d&lt;/code&gt;. Specify&amp;nbsp;an
additional name and &lt;code&gt;psql&lt;/code&gt; will tell you all about that named object.&amp;nbsp;For
example, use &lt;code&gt;\d comments&lt;/code&gt; to list column information of the &lt;code&gt;comments&lt;/code&gt;&amp;nbsp;table:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;psql&amp;gt; \d comments
                                      Table "public.comments"
     Column                 Type                                   Modifiers                       
---------------- --------------------------- -----------------------------------------------------
id               integer                     not null default nextval('comments_id_seq'::regclass)
body             text                        not null
commentable_id   integer                     not null
commentable_type character varying(255)      not null
user_id          integer                     not null
created_at       timestamp without time zone not null
updated_at       timestamp without time zone not null
Indexes:
    "comments_pkey" PRIMARY KEY, btree (id)
    "index_comments_on_commentable_id_and_commentable_type" btree (commentable_id, commentable_type)
    "index_comments_on_user_id" btree (user_id)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;To zoom in on the &lt;code&gt;comments_id_seq&lt;/code&gt; sequence, use&amp;nbsp;&lt;code&gt;\d comments_id_seq&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;    Sequence "public.comments_id_seq"
   Column      Type          Value        
------------- ------- -------------------
sequence_name name    comments_id_seq
last_value    bigint  375
start_value   bigint  1
increment_by  bigint  1
max_value     bigint  9223372036854775807
min_value     bigint  1
cache_value   bigint  1
log_cnt       bigint  21
is_cycled     boolean f
is_called     boolean t
Owned by: public.comments.id
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;I’ve found these commands tell me all I need to know about my database,&amp;nbsp;without
the need to take my hands off the&amp;nbsp;keyboard.&lt;/p&gt;

&lt;h2&gt;Working with&amp;nbsp;results&lt;/h2&gt;

&lt;p&gt;When querying your data, &lt;code&gt;psql&lt;/code&gt; might give you a lot of data — way more than&amp;nbsp;a
single terminal’s screen full. There are several ways to make working with&amp;nbsp;such
data a little&amp;nbsp;easier.&lt;/p&gt;

&lt;h3&gt;Customize the&amp;nbsp;pager&lt;/h3&gt;

&lt;p&gt;&lt;code&gt;psql&lt;/code&gt; will page through the query results using &lt;code&gt;$PAGER&lt;/code&gt;, usually defaulting&amp;nbsp;to
&lt;code&gt;more&lt;/code&gt;.&lt;sup id="fnref:2"&gt;&lt;a href="#fn:2" rel="footnote"&gt;3&lt;/a&gt;&lt;/sup&gt; If you prefer &lt;code&gt;less&lt;/code&gt; (and why wouldn’t you?), you can set&amp;nbsp;the
&lt;code&gt;$PAGER&lt;/code&gt; environment variable or use &lt;code&gt;\setenv PAGER less&lt;/code&gt; at the&amp;nbsp;prompt.&lt;/p&gt;

&lt;h3&gt;Customize the&amp;nbsp;presentation&lt;/h3&gt;

&lt;p&gt;&lt;code&gt;psql&lt;/code&gt; will draw pretty borders between your query columns. You can turn&amp;nbsp;them
off using &lt;code&gt;\pset border 0&lt;/code&gt;, or add even more borders with &lt;code&gt;\pset border 2&lt;/code&gt;.&amp;nbsp;It’s
also nice to use pretty unicode characters to draw those borders by&amp;nbsp;setting
&lt;code&gt;\pset linestyle unicode&lt;/code&gt;. Finally, use wrapped mode to wrap content in&amp;nbsp;columns
with &lt;code&gt;\pset format wrapped&lt;/code&gt; to prevent your columns from running wider than&amp;nbsp;your
screen.&lt;/p&gt;

&lt;p&gt;When there’s so much content and wrapped mode won’t cut it anymore, switch&amp;nbsp;to
vertical mode using &lt;code&gt;\x&lt;/code&gt;. This will display a single column per row, making&amp;nbsp;many
columns or long text values much easier to&amp;nbsp;read.&lt;/p&gt;

&lt;h3&gt;Inspect data in external&amp;nbsp;programs&lt;/h3&gt;

&lt;p&gt;Sometimes you just want to open your results in your editor or a spreadsheet&amp;nbsp;for
further analysis. Use &lt;code&gt;\o data&lt;/code&gt; in the interactive shell (or the command&amp;nbsp;line
argument &lt;code&gt;--output data&lt;/code&gt;) to redirect all output to the file &lt;code&gt;./data&lt;/code&gt;. Note&amp;nbsp;that
&lt;code&gt;data&lt;/code&gt; might also be a script that accepts query results on standard&amp;nbsp;input.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tip&lt;/strong&gt;: for some quick and dirty &lt;span class="caps"&gt;CSV&lt;/span&gt; generation, issue &lt;code&gt;\f ','&lt;/code&gt; to set&amp;nbsp;the
field separator to &lt;code&gt;,&lt;/code&gt;, &lt;code&gt;\a&lt;/code&gt; to switch to unaligned output mode and &lt;code&gt;\t&lt;/code&gt;&amp;nbsp;to
show tuples but no headers or footers. Or, from your shell:&amp;nbsp;&lt;code&gt;psql -d mydb
-t -A -F,&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;Other tweaks and&amp;nbsp;tips&lt;/h2&gt;

&lt;p&gt;One nice customisation to make is tweaking the &lt;code&gt;psql&lt;/code&gt; command prompt. Mine&amp;nbsp;looks
like&amp;nbsp;this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;arjan@mydb
=# SELECT count(*) FROM posts;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The prompt is defined by the special &lt;code&gt;PROMPT1&lt;/code&gt;, &lt;code&gt;PROMPT2&lt;/code&gt; and&amp;nbsp;&lt;code&gt;PROMPT3&lt;/code&gt;
variables. You’ll usually see &lt;code&gt;PROMPT1&lt;/code&gt;; &lt;code&gt;PROMPT2&lt;/code&gt; is used when entering&amp;nbsp;queries
across multiple lines. Some of the special substitutions you can use&amp;nbsp;are:&lt;/p&gt;

&lt;dl&gt;
  &lt;dt&gt;&lt;code&gt;%n&lt;/code&gt;&lt;/dt&gt;
  &lt;dd&gt;The current user&amp;nbsp;name&lt;/dd&gt;
  &lt;dt&gt;&lt;code&gt;%/&lt;/code&gt;&lt;/dt&gt;
  &lt;dd&gt;The current&amp;nbsp;database&lt;/dd&gt;
  &lt;dt&gt;&lt;code&gt;%#&lt;/code&gt;&lt;/dt&gt;
  &lt;dd&gt;&lt;code&gt;&amp;gt;&lt;/code&gt; for regular users, &lt;code&gt;#&lt;/code&gt; for database&amp;nbsp;superusers.&lt;/dd&gt;
  &lt;dt&gt;&lt;code&gt;%R&lt;/code&gt;&lt;/dt&gt;
  &lt;dd&gt;Expected input indicator, hinting when you have unbalanced quotes or missed&amp;nbsp;a
semicolon.&lt;/dd&gt;
  &lt;dt&gt;&lt;code&gt;%x&lt;/code&gt;&lt;/dt&gt;
  &lt;dd&gt;Current transaction status: nothing when there’s no transaction, &lt;code&gt;*&lt;/code&gt; if&amp;nbsp;there
is, &lt;code&gt;!&lt;/code&gt; if the transaction has&amp;nbsp;failed.&lt;/dd&gt;
&lt;/dl&gt;

&lt;h3&gt;Store preferences in&amp;nbsp;.psqlrc&lt;/h3&gt;

&lt;p&gt;If you tweak your &lt;code&gt;psql&lt;/code&gt; preferences it would be nice not to have to&amp;nbsp;reapply
them in every session. Store your customisations in &lt;code&gt;~/.psqlrc&lt;/code&gt; to issue them&amp;nbsp;at
the start of every session. &lt;a href="https://raw.github.com/avdgaag/dotfiles/master/home/.psqlrc"&gt;My .psqlrc file&lt;/a&gt; looks like&amp;nbsp;this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;\set PROMPT1 '%n@%/\n%R%x%# '
\set PROMPT2 '%R%x%# '
\pset border 1
\pset format wrapped
\pset linestyle unicode
\pset null NULL
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;You can then keep that file under source control, along with all your&amp;nbsp;other
dotfiles.&lt;/p&gt;

&lt;h3&gt;Running single&amp;nbsp;commands&lt;/h3&gt;

&lt;p&gt;When you are really in a hurry, or are trying to practice some&amp;nbsp;shell-scripting
magic, you can use the &lt;code&gt;--command&lt;/code&gt; (or &lt;code&gt;-c&lt;/code&gt;) option to &lt;code&gt;psql&lt;/code&gt; to run a&amp;nbsp;one-off
command:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ psql -d mydb -c 'select count(*) from users;' -A -t
58
&lt;/code&gt;&lt;/pre&gt;

&lt;h3&gt;Using connection&amp;nbsp;strings&lt;/h3&gt;

&lt;p&gt;If you have ever wanted to connect to a remote Heroku postgres database,&amp;nbsp;you
know how easy it is to get the connection details from&amp;nbsp;Heroku:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ heroku config:get DATABASE_URL -a myapp
postgres://username@password:very-long-hostname:5432/database
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Try converting that to the appropriate command-line options to &lt;code&gt;psql&lt;/code&gt; to do&amp;nbsp;some
manual prodding around. But, turns out, &lt;code&gt;psql&lt;/code&gt; will accept such a connection&amp;nbsp;&lt;span class="caps"&gt;URI&lt;/span&gt;
just&amp;nbsp;fine:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ psql `heroku config:get DATABASE_URL -a myapp`
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In this particular example, you might as well run &lt;code&gt;heroku pg:psql&lt;/code&gt; as that&amp;nbsp;does
essentially the same thing. But it’s good to know that you &lt;em&gt;can&lt;/em&gt; do this, if&amp;nbsp;you
want&amp;nbsp;to.&lt;/p&gt;

&lt;h2&gt;Conclusion&lt;/h2&gt;

&lt;p&gt;Using the &lt;code&gt;psql&lt;/code&gt; program is much easier than it may seem. Its a good&amp;nbsp;Unix
citizen and it is very simple to integrate into your regular editor.&amp;nbsp;This
interoperability also makes it easy to customise your workflow even further&amp;nbsp;with
scripts and aliases – for example, to automatically connect to the&amp;nbsp;database
described in &lt;code&gt;./config/database.yml&lt;/code&gt; if you’re in a Rails project, or&amp;nbsp;to
automatically download and import data dumps from remote production&amp;nbsp;databases.
Such scripts are left as an exercise to the&amp;nbsp;reader.&lt;/p&gt;

&lt;div class="footnotes"&gt;
  &lt;ol&gt;
    &lt;li id="fn:1"&gt;
      &lt;p&gt;For example, if you are a Vim user, try adding “set editing-mode vi” to &lt;code&gt;~/.inputrc&lt;/code&gt; to enable Vim key bindings in most interactive shells, including &lt;code&gt;psql&lt;/code&gt;.&lt;a href="#fnref:1" rel="reference"&gt;&amp;#8617;&lt;/a&gt;&lt;/p&gt;
    &lt;/li&gt;
    &lt;li id="fn:3"&gt;
      &lt;p&gt;There’s a whole range of &lt;code&gt;\d&lt;/code&gt; metacommands, so read the &lt;code&gt;psql&lt;/code&gt; man pages for more information.&lt;a href="#fnref:3" rel="reference"&gt;&amp;#8617;&lt;/a&gt;&lt;/p&gt;
    &lt;/li&gt;
    &lt;li id="fn:2"&gt;
      &lt;p&gt;The exact program used differs per operating system, but on Mac &lt;span class="caps"&gt;OS&lt;/span&gt; X it seems to default to &lt;code&gt;more&lt;/code&gt;.&lt;a href="#fnref:2" rel="reference"&gt;&amp;#8617;&lt;/a&gt;&lt;/p&gt;
    &lt;/li&gt;
  &lt;/ol&gt;
&lt;/div&gt;
</content>
  </entry>
  <entry>
    <id>tag:arjanvandergaag.nl,2013-01-05:/blog/programming-awk-for-fun-and-profit.html</id>
    <title type="html">Programming Awk for fun and profit</title>
    <published>2013-01-05T13:00:00Z</published>
    <updated>2013-01-05T13:00:00Z</updated>
    <link rel="alternate" href="http://arjanvandergaag.nl/blog/programming-awk-for-fun-and-profit.html"/>
    <content type="html">&lt;p class="leader"&gt;I recently came to learn and love Awk, a “pattern-directed scanning&amp;nbsp;and
processing language”. If you find yourself working with text on a command&amp;nbsp;line
often, you owe it to yourself to learn some&amp;nbsp;Awk.&lt;/p&gt;

&lt;p&gt;Awk is valuable to learn, because in many cases it can replace complex&amp;nbsp;Unix
pipelines consisting of &lt;code&gt;sed&lt;/code&gt;, &lt;code&gt;grep&lt;/code&gt;, &lt;code&gt;cut&lt;/code&gt;, &lt;code&gt;wc&lt;/code&gt; and &lt;code&gt;tr&lt;/code&gt;. It offers&amp;nbsp;a
concise language for text processing that makes it easier to use than Perl&amp;nbsp;or
Ruby. And above all, Awk is so small, it is easy to&amp;nbsp;learn.&lt;/p&gt;

&lt;p&gt;Awk’s main purpose is to extract information from structured text, and&amp;nbsp;report
it in newly combined or aggregated&amp;nbsp;ways.&lt;/p&gt;

&lt;h2&gt;The components of an Awk&amp;nbsp;program&lt;/h2&gt;

&lt;h3&gt;Records and&amp;nbsp;fields&lt;/h3&gt;

&lt;p&gt;The Awk programming language revolves around records and fields. Awk’s&amp;nbsp;purpose
is to parse input into records, parse records into fields, operate on&amp;nbsp;those
records to generate output records and&amp;nbsp;fields.&lt;/p&gt;

&lt;p&gt;In true Unix fashion, by default a record consists of a single line,&amp;nbsp;with
fields separated by whitespace. Naturally, you can customize delimiters&amp;nbsp;using
the special variables &lt;code&gt;RS&lt;/code&gt; and &lt;code&gt;FS&lt;/code&gt; for &lt;em&gt;Record Separator&lt;/em&gt; and &lt;em&gt;Field
Separator&lt;/em&gt; and their output-specific companions &lt;code&gt;ORS&lt;/code&gt; and&amp;nbsp;&lt;code&gt;OFS&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Note that &lt;code&gt;FS&lt;/code&gt; is actually a regular expression, so you can tell Awk to&amp;nbsp;split
on various punctuation characters at once using a value like&amp;nbsp;&lt;code&gt;[| ,()]&lt;/code&gt;.&lt;/p&gt;

&lt;h3&gt;Rules&lt;/h3&gt;

&lt;p&gt;An Awk program always loops over all the records from its input to&amp;nbsp;execute
rules. A &lt;em&gt;rule&lt;/em&gt; consists of a &lt;em&gt;pattern&lt;/em&gt; and an &lt;em&gt;action&lt;/em&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;pattern { action }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;A rule’s action is executed when its pattern matches the current record.&amp;nbsp;The
default pattern matches any record; the default action is to print the&amp;nbsp;current
record.&lt;/p&gt;

&lt;p&gt;Multiple rules in a single program are separated by newlines or&amp;nbsp;semicolons.&lt;/p&gt;

&lt;h3&gt;Patterns&lt;/h3&gt;

&lt;p&gt;Patterns can match record by regular expression, by range or by&amp;nbsp;boolean
expression. Here are a few&amp;nbsp;examples:&lt;/p&gt;

&lt;dl&gt;
  &lt;dt&gt;By regular expression:&amp;nbsp;&lt;code&gt;/foo/&lt;/code&gt;&lt;/dt&gt;
  &lt;dd&gt;Matches when the entire record contains “foo”&amp;nbsp;somewhere.&lt;/dd&gt;
  &lt;dt&gt;By boolean expression:&amp;nbsp;&lt;code&gt;$2 ~ /foo/&lt;/code&gt;&lt;/dt&gt;
  &lt;dd&gt;Matches when the second field matches the regular expression&amp;nbsp;&lt;code&gt;foo&lt;/code&gt;.&lt;/dd&gt;
  &lt;dt&gt;By boolean expression:&amp;nbsp;&lt;code&gt;NR % 2&lt;/code&gt;&lt;/dt&gt;
  &lt;dd&gt;Matches all uneven records (lines), because &lt;code&gt;NR&lt;/code&gt; is a special&amp;nbsp;variable
containing the current record number and &lt;code&gt;0&lt;/code&gt; is&amp;nbsp;falsy.&lt;/dd&gt;
  &lt;dt&gt;By range:&amp;nbsp;&lt;code&gt;/foo/, /bar/&lt;/code&gt;&lt;/dt&gt;
  &lt;dd&gt;Using the comma notation, this matches every record from the first to&amp;nbsp;contain
&lt;code&gt;foo&lt;/code&gt; up to and including the next that contains &lt;code&gt;bar&lt;/code&gt;. For example, you&amp;nbsp;can
print a table definition from a Ruby on Rails db/schema.rb file&amp;nbsp;using
&lt;code&gt;awk '/create_table "users"/, /^  end/' db/schema.rb&lt;/code&gt;.&lt;/dd&gt;
  &lt;dt&gt;&lt;code&gt;BEGIN&lt;/code&gt; and&amp;nbsp;&lt;code&gt;END&lt;/code&gt;&lt;/dt&gt;
  &lt;dd&gt;Run a block of code before or after looping over all the input. This&amp;nbsp;is
useful for setting up arrays, modifying special variables and&amp;nbsp;presenting
aggregated&amp;nbsp;results.&lt;/dd&gt;
&lt;/dl&gt;

&lt;h3&gt;Actions&lt;/h3&gt;

&lt;p&gt;While the default action of printing the current action already makes Awk&amp;nbsp;an
interesting alternative to grep, custom actions make Awk truly&amp;nbsp;powerful.&lt;/p&gt;

&lt;p&gt;Actions can contain entire programs using loops, variables, functions&amp;nbsp;and
conditionals – but in the end they usually come down to printing information&amp;nbsp;to
the output&amp;nbsp;stream.&lt;/p&gt;

&lt;p&gt;For example, you can print columns from the input record using the special&amp;nbsp;&lt;code&gt;$&lt;/code&gt;
function:&lt;sup id="fnref:1"&gt;&lt;a href="#fn:1" rel="footnote"&gt;1&lt;/a&gt;&lt;/sup&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;{ print $2, $1 }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This program prints the first two columns of every record in reverse order.&amp;nbsp;To
have a little more control over output formatting, you can use the&amp;nbsp;familiar
&lt;code&gt;printf&lt;/code&gt;&amp;nbsp;function:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;{ printf "%6s: $%.2f", $1, $2 }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This will print the first input column as six characters wide,&amp;nbsp;right-aligned
string; and the second as monetary&amp;nbsp;value. &lt;/p&gt;

&lt;h3&gt;Advanced Awk&amp;nbsp;programming&lt;/h3&gt;

&lt;p&gt;Awk is a surprisingly complete programming language. Consider the&amp;nbsp;following
example&amp;nbsp;program:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;BEGIN { max = 0 }
{ if($1 &amp;gt; max) max = $1 }
END { print max }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This simple program demonstrates the use of variables and conditionals to&amp;nbsp;find
the biggest value in the first&amp;nbsp;column.&lt;/p&gt;

&lt;p&gt;Consider the following&amp;nbsp;example:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;{ categories[$2]++ }
END {
  for(key in categories) {
    print key, categories[key]
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This program builds a histogram of the second column, outputting each&amp;nbsp;unique
value found in the second column of its input, following by how many times&amp;nbsp;that
value was found. Note the use of an &lt;a href="http://www.math.utah.edu/docs/info/gawk_12.html"&gt;associative array&lt;/a&gt; and the &lt;code&gt;for(key in
array)&lt;/code&gt;&amp;nbsp;loop.&lt;/p&gt;

&lt;p&gt;Finally, Awk allows you to use a set of &lt;a href="http://www.math.utah.edu/docs/info/gawk_13.html"&gt;built-in functions&lt;/a&gt; and&amp;nbsp;even
&lt;a href="http://www.math.utah.edu/docs/info/gawk_14.html"&gt;define your own&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;Running Awk&amp;nbsp;programs&lt;/h2&gt;

&lt;p&gt;The simplest way to use Awk is on the command line, for example to print&amp;nbsp;known
usernames:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ awk -F: '{ print $1 }' /etc/passwd
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Awk will read its first non-option argument as the program to run, and&amp;nbsp;any
other arguments as files to read. Awk will gladly accept multiple files as&amp;nbsp;one
big input stream. Of course, it will also work fine in a Unix&amp;nbsp;pipeline.&lt;/p&gt;

&lt;p&gt;When your programs get too large to comfortably write at a command prompt,&amp;nbsp;you
could put it in a file and tell Awk to run&amp;nbsp;it:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ awk -f my_program.awk /etc/passwd
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Alternatively, as Awk also functions as an interpreter, you can write your&amp;nbsp;Awk
programs in an executable file. In a file called&amp;nbsp;&lt;code&gt;usernames.awk&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;#!/usr/bin/awk -f
BEGIN { FS = ":" }
{ print $1 }
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Make the file executable with &lt;code&gt;chmod +x usernames.awk&lt;/code&gt; and invoke it&amp;nbsp;with
&lt;code&gt;./usernames.awk /etc/passwd&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;Example&amp;nbsp;program&lt;/h2&gt;

&lt;p&gt;Here is an example (prettified) script that parses some server log&amp;nbsp;files,
containing information about products fetched from a remote server and&amp;nbsp;the
total amount of time that took. We want to create a histogram showing&amp;nbsp;time
intervals and the total number of products in that category. The logs&amp;nbsp;contain
some lines that look like&amp;nbsp;this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;[CatalogItem] Retrieved 12 product, expected 46 (1837.8ms)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This program is composed of several Awk scripts piped together, with a&amp;nbsp;&lt;code&gt;sort&lt;/code&gt;
thrown in as&amp;nbsp;well.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ awk -F '[ ()]|ms' '
  # Construct an array of categories of average request times
  # and the number of products in that category.
  /\[CatalogItem\] Retrieved/ {
    number_of_products = $6
    total_request_time = $8
    average_response_time = nummber_of_products / total_request_time
    categories[int(average_response_time)] += number_of_products
  }

  # When all lines have been read, print the results
  END {
    for(label in categories) {
      print label, categories[l]
    }
  }
  ' production.log
  |
  awk '
    BEGIN {
      max = 0
    }
    # Loop over all records to find the highest frequency
    # in the histogram
    {
      if($2 &amp;gt; max) {
        max = $2
      }
      categories[$1] = $2
    }
    # Print the histogram again, but relate all frequencies to the
    # maximum we found
    END {
      for(label in categories) {
        printf("%5d %d\n", label, categories[label] / max)
      }
    }
  '
  |
  awk '
    {
      # Construct a visual bar sized by the histogram frequency
      # in the second column. Note that Awk's string concatenation
      # operator is the space.
      bar = ""
      size = $2
      while(size-- &amp;gt; 0) {
        bar = bar "#"
      }

      # Print the original histogram labels and the generated bar.
      printf("%6d %s\n", $1, bar)
    }
  '
  |
  sort -n
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This program will output something&amp;nbsp;like:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;     0 ##
   100 ######
   200 ###############
   300 #########
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Conclusion&lt;/h2&gt;

&lt;p&gt;Search around the web and you’ll find dozens of pages with Awk one-liners to&amp;nbsp;do
all sorts of crazy text manipulation stuff. They’re a good resource to pick&amp;nbsp;up
new ideas from, but the power of Awk lies not in building libraries of&amp;nbsp;text
processing functions, but rather in the ability to quickly whip up&amp;nbsp;custom
scripts to handle unique circumstances. Master Awk and be&amp;nbsp;creative!&lt;/p&gt;
&lt;div class="footnotes"&gt;
  &lt;ol&gt;
    &lt;li id="fn:1"&gt;
      &lt;p&gt;Since &lt;code&gt;$&lt;/code&gt; is a function, you could use expressions to retrieve a&amp;nbsp;dynamic
  column number, i.e. &lt;code&gt;n = NR % 2; print $n&lt;/code&gt;.&lt;a href="#fnref:1" rel="reference"&gt;&amp;#8617;&lt;/a&gt;&lt;/p&gt;
    &lt;/li&gt;
  &lt;/ol&gt;
&lt;/div&gt;
</content>
  </entry>
  <entry>
    <id>tag:arjanvandergaag.nl,2012-08-23:/blog/modular-front-end-code-in-rails.html</id>
    <title type="html">Modular front-end code in Rails</title>
    <published>2012-08-23T10:00:00Z</published>
    <updated>2012-08-23T10:00:00Z</updated>
    <link rel="alternate" href="http://arjanvandergaag.nl/blog/modular-front-end-code-in-rails.html"/>
    <content type="html">&lt;p class="leader"&gt;Maintainable stylesheets of non-trivial size need a modular design — so much has been established by now. How can you incorporate this style of front-end coding in a typical Rails&amp;nbsp;application?&lt;/p&gt;

&lt;h2&gt;Modular&amp;nbsp;&lt;span class="caps"&gt;CSS&lt;/span&gt;&lt;/h2&gt;

&lt;p&gt;With ‘Modular &lt;span class="caps"&gt;CSS&lt;/span&gt;’ I mean a range of new ideas in front-end web&amp;nbsp;development
aiming to solve some of the issues with giant catch-all .css-files,&amp;nbsp;rife
with duplication and specificity conflicts. These approaches&amp;nbsp;typically
revolve around defining “objects”, “modules” or “components” in&amp;nbsp;your
stylesheets, in order to reduce the cost of change&amp;nbsp;by:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;increasing style re-use and, by extension,&amp;nbsp;consistency;&lt;/li&gt;
  &lt;li&gt;creating a shared language among team&amp;nbsp;members;&lt;/li&gt;
  &lt;li&gt;decoupling markup from&amp;nbsp;styles.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;To learn more about these ideas, check out &lt;a href="http://www.stubbornella.org"&gt;Nicole Sullivan&lt;/a&gt;’s
&lt;a href="http://oocss.org"&gt;Object-Oriented &lt;span class="caps"&gt;CSS&lt;/span&gt;&lt;/a&gt;, &lt;a href="http://snook.ca"&gt;Jonathan Snook&lt;/a&gt;’s &lt;a href="http://smacss.com"&gt;&lt;span class="caps"&gt;SMACSS&lt;/span&gt;&lt;/a&gt;, Yandex’ &lt;a href="http://bem.github.com/bem-method/pages/beginning/beginning.en.html"&gt;&lt;span class="caps"&gt;BEM&lt;/span&gt;&lt;/a&gt; and keep an eye out for &lt;a href="http://roytomeij.com"&gt;Roy Tomeij&lt;/a&gt;’s book &lt;a href="http://modular-frontend.com"&gt;Modular Frontend&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;Modular front-end code in Rails&amp;nbsp;apps&lt;/h2&gt;

&lt;p&gt;Historically, Rails has “forced” many best practices on developers&amp;nbsp;by
providing conventions for trivial matters (see &lt;a href="http://www.confreaks.com/videos/907-railsconf2012-rails-the-next-five-years"&gt;Yehuda Katz’s&amp;nbsp;RailsConf
2012 talk&lt;/a&gt; for examples and background). But to&amp;nbsp;properly
modularize our front-end code, we have to fight Rails a little bit and&amp;nbsp;rid
ourselves of the “one controller, one stylesheet, one script” default&amp;nbsp;file
layout. At the same time, Rails does provide us with some nice tools&amp;nbsp;to
make our jobs easier: the &lt;a href="http://guides.rubyonrails.org/asset_pipeline.html"&gt;asset pipeline&lt;/a&gt;, &lt;a href="http://sass-lang.com"&gt;Sass&lt;/a&gt; included by default, and&amp;nbsp;&lt;code&gt;RecordTagHelper&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Note&lt;/strong&gt;: in this post I’m ignoring the Javascript aspect of front-end code on purpose. That’s a story for another&amp;nbsp;time.&lt;/p&gt;

&lt;h2&gt;Marking up&amp;nbsp;objects&lt;/h2&gt;

&lt;p&gt;The modularized front-end revolves around identifying the building blocks of your web pages, like a &lt;em&gt;post&lt;/em&gt;, a &lt;em&gt;footer&lt;/em&gt; or a &lt;em&gt;horizontal list&lt;/em&gt;. Rails’ &lt;code&gt;content_tag_for&lt;/code&gt; is a great help to mark these objects&amp;nbsp;up:&lt;/p&gt;

&lt;pre lang="erb"&gt;&lt;code&gt;&amp;lt;%= content_tag_for(:article, @posts) do |post| %&amp;gt;
  &amp;lt;h2&amp;gt;&amp;lt;%= post.title %&amp;gt;&amp;lt;/h2&amp;gt;
  &amp;lt;div class="content"&amp;gt;
    &amp;lt;%= markdown post.body %&amp;gt;
  &amp;lt;/div&amp;gt;
&amp;lt;% end %&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This might generate the following&amp;nbsp;output:&lt;/p&gt;

&lt;pre lang="html"&gt;&lt;code&gt;&amp;lt;article id="post_1" class="post"&amp;gt;
  &amp;lt;h2&amp;gt;My example post&amp;lt;/h2&amp;gt;
  &amp;lt;div class="content"&amp;gt;
    &amp;lt;p&amp;gt;Foo bar&amp;lt;/p&amp;gt;
  &amp;lt;/div&amp;gt;
&amp;lt;/article&amp;gt;
&amp;lt;article id="post_2" class="post"&amp;gt;
  &amp;lt;h2&amp;gt;Another example post&amp;lt;/h2&amp;gt;
  &amp;lt;div class="content"&amp;gt;
    &amp;lt;p&amp;gt;baz qux&amp;lt;/p&amp;gt;
  &amp;lt;/div&amp;gt;
&amp;lt;/article&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Rails gives us a convention for naming and identifying objects. You&amp;nbsp;would
typically provide styles for the &lt;code&gt;.post&lt;/code&gt; class, and attach&amp;nbsp;javascript
behaviour to individual posts using the &lt;code&gt;#post_1&lt;/code&gt; and &lt;code&gt;#post_2&lt;/code&gt;&amp;nbsp;IDs.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Note&lt;/strong&gt;: There is also a &lt;code&gt;div_for&lt;/code&gt; tag, which does basically the same&amp;nbsp;as
&lt;code&gt;content_tag_for&lt;/code&gt; but omits the first argument and always gives you&amp;nbsp;a
&lt;code&gt;div&lt;/code&gt;. For more information, see the documentation&amp;nbsp;on
&lt;a href="http://api.rubyonrails.org/classes/ActionView/Helpers/RecordTagHelper.html"&gt;ActionView::Helpers::RecordTagHelper&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;If &lt;a href="http://haml.info"&gt;Haml&lt;/a&gt; is more your cup of tea, you could&amp;nbsp;write:&lt;/p&gt;

&lt;pre lang="haml"&gt;&lt;code&gt;%div[post]
  %h2= post.title
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;If you are not dealing with instances of &lt;code&gt;ActiveRecord::Base&lt;/code&gt;, you can&amp;nbsp;still
use these helpers by defining some extra methods on your objects, as&amp;nbsp;these
classes and IDs are generated as &lt;code&gt;"#{object.param_key}_#{object.to_key}"&lt;/code&gt;.&amp;nbsp;Take
a look at &lt;a href="http://api.rubyonrails.org/classes/ActiveModel/Naming.html"&gt;&lt;code&gt;ActiveModel::Naming&lt;/code&gt;&lt;/a&gt;&amp;nbsp;and
&lt;a href="http://api.rubyonrails.org/classes/ActionController/RecordIdentifier.html"&gt;&lt;code&gt;ActionController::RecordIdentifier&lt;/code&gt;&lt;/a&gt; for&amp;nbsp;details.&lt;/p&gt;

&lt;h2&gt;Object&amp;nbsp;inheritence&lt;/h2&gt;

&lt;p&gt;You will usually find yourself needing to go one step further and&amp;nbsp;apply
object inheritence: a post can take many different forms on your&amp;nbsp;site,
ranging from full articles, excerpts in an index or links in a&amp;nbsp;sidebar.
Rails can still help&amp;nbsp;us:&lt;/p&gt;

&lt;pre lang="erb"&gt;&lt;code&gt;&amp;lt;%- content_tag_for(:article, @posts, :excerpt) do |post| %&amp;gt;
  ...
&amp;lt;% end %&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Will give&amp;nbsp;us:&lt;/p&gt;

&lt;pre lang="html"&gt;&lt;code&gt;&amp;lt;article id="excerpt_post_123" class="excerpt_post"&amp;gt;
  ...
&amp;lt;/article&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Although I would have preferred dashes insteads of underscores, Rails&amp;nbsp;still
makes a trivial decision on how to name stuff for us, so let’s stick with&amp;nbsp;it.&lt;/p&gt;

&lt;h2&gt;Partials, paths and&amp;nbsp;&lt;span class="caps"&gt;STI&lt;/span&gt;&lt;/h2&gt;

&lt;p&gt;It is a natural fit to use a partial for every object you define. So,&amp;nbsp;to
render blog post excerpts on your front page, you will end up with&amp;nbsp;a
&lt;code&gt;posts/_excerpt_post&lt;/code&gt; partial and a&amp;nbsp;&lt;code&gt;modules/posts/excerpt_post.css.scss&lt;/code&gt;
stylesheet. It is now trivial to render an excerpt post object anywere&amp;nbsp;in
your&amp;nbsp;application:&lt;/p&gt;

&lt;pre lang="erb"&gt;&lt;code&gt;&amp;lt;%= render partial: 'posts/excerpt_post', collection: @posts %&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Should you create custom Ruby objects — such as decorated models&amp;nbsp;or
presenters that group multiple persistence objects into a single&amp;nbsp;business
object — you may want to define &lt;code&gt;to_partial_path&lt;/code&gt; on it to tell Rails how&amp;nbsp;to
render&amp;nbsp;them:&lt;/p&gt;

&lt;pre lang="ruby"&gt;&lt;code&gt;require 'delegate'
class ArticlePresenter &amp;lt; DelegateClass(Post)
  def to_partial_path
    'posts/article_post'
  end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Which would allow you to render an instance of &lt;code&gt;ArticlePresenter&lt;/code&gt; like&amp;nbsp;so:&lt;/p&gt;

&lt;pre lang="erb"&gt;&lt;code&gt;&amp;lt;%= render article_presenter %&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;…and have it use the &lt;code&gt;posts/_article_post.html.erb&lt;/code&gt;&amp;nbsp;template.&lt;/p&gt;

&lt;p&gt;Finally, Rails’ Single Table Inheritance can get in your way. Consider&amp;nbsp;you
have set up your models so that both &lt;code&gt;Post&lt;/code&gt; and &lt;code&gt;Page&lt;/code&gt; inherit from&amp;nbsp;a
generic &lt;code&gt;Node&lt;/code&gt; model. Using &lt;code&gt;content_tag_for&lt;/code&gt; will give you &lt;code&gt;.post&lt;/code&gt;&amp;nbsp;and
&lt;code&gt;.page&lt;/code&gt; classes. If you want to use the same styles for all&amp;nbsp;&lt;code&gt;Node&lt;/code&gt;
subtypes, you could apply the same styles to both classes in&amp;nbsp;your
stylesheet, or you could use&amp;nbsp;&lt;code&gt;ActiveRecord::Base#becomes&lt;/code&gt;:&lt;/p&gt;

&lt;pre lang="erb"&gt;&lt;code&gt;&amp;lt;%= content_tag_for(:div, @post.becomes(Node)) do %&amp;gt;
  &amp;lt;h2&amp;gt;&amp;lt;%= @post.title %&amp;gt;&amp;lt;/h2&amp;gt;
&amp;lt;% end %&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;code&gt;becomes&lt;/code&gt; will give you a new &lt;code&gt;Node&lt;/code&gt; object with all the attributes of&amp;nbsp;the
&lt;code&gt;@post&lt;/code&gt; object, so you will end up with the proper &lt;code&gt;.node&lt;/code&gt; class on&amp;nbsp;your
object. You can also use this trick to render child class using the&amp;nbsp;partial
that would have been used for the parent&amp;nbsp;class:&lt;/p&gt;

&lt;pre lang="erb"&gt;&lt;code&gt;&amp;lt;%= render @posts.map { |p| p.becomes(Node) } %&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;See the &lt;a href="http://api.rubyonrails.org/classes/ActiveRecord/Persistence.html#method-i-becomes"&gt;documentation on &lt;code&gt;#becomes&lt;/code&gt;&lt;/a&gt; and read &lt;a href="http://henrik.nyh.se"&gt;Henrik Nyh&lt;/a&gt;’s notes on &lt;a href="http://henrik.nyh.se/2012/08/rails-sti-and-form-for/"&gt;using &lt;code&gt;becomes&lt;/code&gt; with form helpers&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;Styling&amp;nbsp;objects&lt;/h2&gt;

&lt;p&gt;Now you’ve got your &lt;code&gt;.post&lt;/code&gt; object and various sub types, such as &lt;code&gt;.excerpt_post&lt;/code&gt; set up. These are now trivial to style using Sass and the &lt;code&gt;@extend&lt;/code&gt;&amp;nbsp;directive:&lt;/p&gt;

&lt;pre lang="css"&gt;&lt;code&gt;.post {
  h2 {
    color: #f00;
    margin: 20px 0;
  }
}

.excerpt_post {
    @extend .post;
  h2 {
    margin: 0;
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Which would result in something&amp;nbsp;like:&lt;/p&gt;

&lt;pre lang="css"&gt;&lt;code&gt;.post h2, .excerpt_post h2 {
  color: #f00;
  margin: 20px 0;
}
.excerpt_post h2 {
  margin: 0;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;With Sass &lt;span class="caps"&gt;3.2&lt;/span&gt;, you might even keep the base &lt;code&gt;.post&lt;/code&gt; class from the final style sheet — since you will most probably never use it on its own. Just use a placeholder&amp;nbsp;selector:&lt;/p&gt;

&lt;pre lang="css"&gt;&lt;code&gt;%post {
  color: #333;
}
.excerpt_post {
  @extend %post;
  font-size: 12px;
}
.article_post {
  @extend %post;
  font-size: 14px;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This leads to the base class not being output, only the&amp;nbsp;extensions:&lt;/p&gt;

&lt;pre lang="css"&gt;&lt;code&gt;.excerpt_post, .article_post {
  color: #333;
}
.excerpt_post {
  font-size: 12px;
}
.article_post {
  font-size: 14px;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Catches&lt;/h2&gt;

&lt;p&gt;Much like object-oriented programming, we can define generic styles for all post objects, and add special styles to special instances. Also much like object-oriented programming, note that  that you ‘child’-objects should not differ too much from your ‘parent’-object; even though you are technically displaying a post object, it may be a better idea to classify your sidebar link item as a “link” rather than a “post”. Here, Rails leaves you on your own and you will have to write your markup&amp;nbsp;yourself:&lt;/p&gt;

&lt;pre lang="erb"&gt;&lt;code&gt;&amp;lt;li id="link_&amp;lt;%= post.id -%&amp;gt;" class="link"&amp;gt;
  &amp;lt;%= link_to post.title, post %&amp;gt;
&amp;lt;/li&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This is a nuisance, but it would be trivial to write a helper method for&amp;nbsp;it.
I haven’t come across it much in&amp;nbsp;practice.&lt;/p&gt;

&lt;h2&gt;Don’t forget about&amp;nbsp;mixins&lt;/h2&gt;

&lt;p&gt;Regardless, it is clear it makes sense to think about your object&amp;nbsp;hierarchy
before your build it. Also, as Ruby itself shows us with its modules,&amp;nbsp;not
everything is modelled best with a hieriarchical structure. Consider mixins&amp;nbsp;to
share styles across object&amp;nbsp;types:&lt;/p&gt;

&lt;pre lang="css"&gt;&lt;code&gt;@mixin sidebar_link {
  font-weight: bold;
}
.link_post {
  @include sidebar_link;
}
.link_comment {
  @include sidebar_link;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Organising your&amp;nbsp;files&lt;/h2&gt;

&lt;p&gt;Using the aforementioned techniques, you will quickly end up with a bunch&amp;nbsp;of
styled objects. It is probably best to abandon Rails’ convention&amp;nbsp;of
one-stylesheet-per-controller and keep each in a separate file using the&amp;nbsp;module
pattern:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;app/
|--assets/
|  |--stylesheets/
|  |  |--application.css
|  |  |--layout.css.scss
|  |  |--elements.css.scss
|  |  |--modules/
|  |  |  |--post.css.scss
|  |  |  |--excerpt_post.css.scss
|  |  |  |--link_post.css.scss
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;Tip&lt;/strong&gt;: When using Rails generators, you can provide the &lt;code&gt;--no-assets&lt;/code&gt;&amp;nbsp;or
&lt;code&gt;--no-stylesheets&lt;/code&gt; flag (along with &lt;code&gt;--no-helper&lt;/code&gt;) to not generate the&amp;nbsp;regular
asset files you are not going to use&amp;nbsp;anyway.&lt;/p&gt;

&lt;p&gt;Your modules directory quickly clutters up so you had better group them&amp;nbsp;in
subdirectories:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;app/
|--assets/
|  |--stylesheets/
|  |  |--application.css
|  |  |--layout.css.scss
|  |  |--elements.css.scss
|  |  |--modules/
|  |  |  |--posts/
|  |  |  |  |--post.css.scss
|  |  |  |  |--excerpt_post.css.scss
|  |  |  |  |--link_post.css.scss
|  |  |  |--comments/
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Concatenating&amp;nbsp;assets&lt;/h2&gt;

&lt;p&gt;With so many files lying around, it would of course be great if you&amp;nbsp;could
include them all in one fell swoop, rather than importing each by hand in&amp;nbsp;the
&lt;code&gt;application.css&lt;/code&gt; manifest file. Sprockets can do that for&amp;nbsp;you:&lt;/p&gt;

&lt;pre lang="css"&gt;&lt;code&gt;/*
 * in app/assets/stylesheets/application.css
 * require_tree .
 */
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Done! But Sprockets, alas, will first compile every file and &lt;em&gt;then&lt;/em&gt;&amp;nbsp;concatenate
them together. Now Sass will no longer be able to use mixins and variables&amp;nbsp;from
one file in another. This is a disappointment, so you will have to&amp;nbsp;bypass
Sprockets for concatenation and let Sass handle it for you.&amp;nbsp;Rename
&lt;code&gt;application.css&lt;/code&gt; to &lt;code&gt;application.css.scss&lt;/code&gt; and let the &lt;a href="https://github.com/rails/sass-rails"&gt;sass-rails&lt;/a&gt;&amp;nbsp;gem
handle the importing for&amp;nbsp;your:&lt;/p&gt;

&lt;pre lang="css"&gt;&lt;code&gt;// in app/assets/stylesheets/application.css.scss
@import "modules/**/*"
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This approach imports your modules sorted alphabetically, which is a great&amp;nbsp;way
to foce yourself to write truly independent modules that do not depend on&amp;nbsp;the
order in which they are defined. In practice, this might not work out, in&amp;nbsp;which
case you will have to revert to importing every module by hand in your&amp;nbsp;manifest
stylesheet.&lt;/p&gt;

&lt;h2&gt;Conclusion&lt;/h2&gt;

&lt;p&gt;There’s a little bit of friction when adopting these methods in your&amp;nbsp;Rails
application, but for the most part it is easy to get started and Rails has&amp;nbsp;some
nice convenience methods for us to use. With a little bit of discipline you&amp;nbsp;can
set up a very neat and organised front-end codebase — just make sure&amp;nbsp;your
approach is documented so all your team members are on the same page with&amp;nbsp;you.&lt;/p&gt;

&lt;p&gt;If you have any other tips, &lt;a href="http://twitter.com/avdgaag"&gt;let me know on Twitter&lt;/a&gt;!&lt;/p&gt;

</content>
  </entry>
  <entry>
    <id>tag:arjanvandergaag.nl,2012-07-01:/blog/vim-advanced-search-and-replace.html</id>
    <title type="html">Vim advanced search and replace</title>
    <published>2012-07-01T10:00:00Z</published>
    <updated>2012-07-01T10:00:00Z</updated>
    <link rel="alternate" href="http://arjanvandergaag.nl/blog/vim-advanced-search-and-replace.html"/>
    <content type="html">&lt;p class="leader"&gt;When I get a few days off from work, I do what every self-respecting geek&amp;nbsp;would
do: I dive into my text editor and try to learn some new stuff. Here’s a&amp;nbsp;few
    tricks I learned recently concerning search and replace in&amp;nbsp;Vim.&lt;/p&gt;

&lt;h2&gt;1. Indenting a multi-line search&amp;nbsp;match&lt;/h2&gt;

&lt;p&gt;Say you have a Markdown document with code blocks marked up in&amp;nbsp;Github-style
‘fences’:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Here is a code example:

```ruby
puts "Hello, world"
```
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;You want to convert these code blocks to standard Markdown code blocks –&amp;nbsp;which
have no fences, but instead are indented four spaces. This is desired&amp;nbsp;end
result:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Here is a code example:

    puts "Hello, world"
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The example includes only a single code block with a single line of code,&amp;nbsp;but
let’s assume there’s several multi-line code blocks. How to go about&amp;nbsp;this
problem?&lt;/p&gt;

&lt;p&gt;My first attempt was to use a regular expression search to match the&amp;nbsp;entire
code block, and then find some way to perform the indent command on&amp;nbsp;its
matches. The regular expression is not too hard, once you know the relevant&amp;nbsp;Vim
regular expression&amp;nbsp;syntax:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;/\v^```ruby\_.{-1,}```$/
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Note the &lt;code&gt;\v&lt;/code&gt; for &lt;a href="http://vimdoc.sourceforge.net/htmldoc/pattern.html#/magic"&gt;very magic syntax&lt;/a&gt;, &lt;code&gt;\_.&lt;/code&gt; to &lt;a href="http://vimdoc.sourceforge.net/htmldoc/pattern.html#/\_."&gt;match&amp;nbsp;any
character&lt;/a&gt; (including newlines) and &lt;code&gt;{-1,}&lt;/code&gt; to &lt;a href="http://vimdoc.sourceforge.net/htmldoc/pattern.html#/\{-"&gt;non-greedily
match&lt;/a&gt; at least one of&amp;nbsp;&lt;code&gt;\_.&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;This search matches all the fenced code blocks alright, so we need a way&amp;nbsp;to
operate on every match. Here the &lt;a href="http://vimdoc.sourceforge.net/htmldoc/repeat.html#:g"&gt;global command&lt;/a&gt; (&lt;code&gt;g&lt;/code&gt;) comes&amp;nbsp;into
play. Here’s my first attempt to indent every&amp;nbsp;match:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;:g/\v```ruby\_.{-1,}```$/&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The global command allows you to operate on every line matching a pattern,&amp;nbsp;in
this case using the &lt;code&gt;&amp;gt;&lt;/code&gt; command to indent lines. Alas, only the first line&amp;nbsp;of
the match would indent, giving&amp;nbsp;me:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Here is a code example:

    ```ruby
puts "Hello, world"
```
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;My misunderstanding was that a multi-line search would match multiple lines&amp;nbsp;–
instead, a search in Vim is found on &lt;em&gt;a single line&lt;/em&gt; (which makes sense&amp;nbsp;when
you think about&amp;nbsp;it).&lt;/p&gt;

&lt;p&gt;After some Googling for search operations, I found the global command sets&amp;nbsp;the
current line in vim to the line of the search match. From there, you can&amp;nbsp;start
a new range up to the closing fence and operate on that range with the&amp;nbsp;indent
command. Here’s&amp;nbsp;how:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;:g/^```ruby/.,/```$/&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;So, to recap: &lt;code&gt;g/^```ruby/&lt;/code&gt; searches for our opening fence and&amp;nbsp;sets
Vim’s &lt;em&gt;current line&lt;/em&gt; to that line. The rest of the command is the operation&amp;nbsp;on
that line. &lt;code&gt;.,/```$/&lt;/code&gt; is a &lt;a href="http://vimdoc.sourceforge.net/htmldoc/cmdline.html#:range"&gt;range&lt;/a&gt;. We might express ranges&amp;nbsp;with
line numbers (i.e. &lt;code&gt;10,20&lt;/code&gt;), but we can also use special symbols and&amp;nbsp;searches.
In this case, &lt;code&gt;.&lt;/code&gt; is the current line (the one with the opening fence), and&amp;nbsp;we
end our range on the first match from our current line that matches our&amp;nbsp;closing
line. Finally, we can operate on a range using any ex command&lt;sup id="fnref:1"&gt;&lt;a href="#fn:1" rel="footnote"&gt;1&lt;/a&gt;&lt;/sup&gt;, in this&amp;nbsp;case
&lt;code&gt;&amp;gt;&lt;/code&gt; to indent.&amp;nbsp;Success!&lt;/p&gt;

&lt;h2&gt;2. Solve your problems with external&amp;nbsp;tools&lt;/h2&gt;

&lt;p&gt;It later occured to me the above problem might just as well have been&amp;nbsp;solved
using Ruby. Here’s an example&amp;nbsp;solution:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;:%!ruby -pe "gsub /^/, '    ' if /^```ruby/../```$/"
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;We use &lt;code&gt;%!&lt;/code&gt; to filter the entire file through the &lt;code&gt;ruby&lt;/code&gt; program. The &lt;code&gt;-p&lt;/code&gt;&amp;nbsp;flag
to Ruby tells it to loop over &lt;code&gt;STDIN&lt;/code&gt; and print every line back to&amp;nbsp;&lt;code&gt;STDOUT&lt;/code&gt;.
The &lt;code&gt;-e&lt;/code&gt; flag to Ruby evaluates a string of Ruby code. Since &lt;code&gt;-p&lt;/code&gt; put Ruby&amp;nbsp;in
the special command-line mode, &lt;code&gt;gsub&lt;/code&gt; and and regular expressions&amp;nbsp;are
implicitly sent to the current line. The above string of Ruby code&amp;nbsp;is
equivalent to the following&amp;nbsp;program:&lt;/p&gt;

&lt;pre lang="ruby"&gt;&lt;code&gt;while $_ = STDIN.gets
  if $_ =~ /^```ruby/../```$/
    $_.gsub! /^/, '    '
  end
  print $_
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Finally, the regular expression range syntax (also known as the &lt;a href="http://www.ruby-doc.org/docs/ProgrammingRuby/html/tut_expressions.html#S6"&gt;flip-flop
operator&lt;/a&gt;) is one of those awesome Ruby tricks few people&amp;nbsp;know:
looping over several lines, it becomes true when the left-hand regex&amp;nbsp;matches,
and stays true on subsequent tests until the right-hand side regex&amp;nbsp;matches.&lt;/p&gt;

&lt;p&gt;Is the Ruby alternative more readable than the Vim one? You decide for&amp;nbsp;yourself
– just know there’s more than one way to skin a&amp;nbsp;cat.&lt;/p&gt;

&lt;h2&gt;3. Adding an incrementing counter to search&amp;nbsp;matches&lt;/h2&gt;

&lt;p&gt;A while back I had an &lt;span class="caps"&gt;HTML&lt;/span&gt; document with sixteen headers I wanted to&amp;nbsp;prefix
with an incrementing number. I wanted to turn&amp;nbsp;this:&lt;/p&gt;

&lt;pre lang="html"&gt;&lt;code&gt;&amp;lt;h3&amp;gt;Heading 1&amp;lt;/h3&amp;gt;
&amp;lt;p&amp;gt;Lorem ipsum&amp;lt;/p&amp;gt;
&amp;lt;h3&amp;gt;Heading 2&amp;lt;/h3&amp;gt;
&amp;lt;p&amp;gt;Lorem ipsum&amp;lt;/p&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;…into&amp;nbsp;this:&lt;/p&gt;

&lt;pre lang="html"&gt;&lt;code&gt;&amp;lt;h3&amp;gt;1. Heading 1&amp;lt;/h3&amp;gt;
&amp;lt;p&amp;gt;Lorem ipsum&amp;lt;/p&amp;gt;
&amp;lt;h3&amp;gt;2. Heading 2&amp;lt;/h3&amp;gt;
&amp;lt;p&amp;gt;Lorem ipsum&amp;lt;/p&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;I accomplished it with Vim’s search-and-replace capabilities and a&amp;nbsp;little
vimscript, taking advantage of &lt;code&gt;\=&lt;/code&gt;, which allows us to &lt;a href="http://vimdoc.sourceforge.net/htmldoc/change.html#:s\="&gt;use an expression&amp;nbsp;in
the substitue string&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;The first step to solving this problem is matching the right characters&amp;nbsp;for
replacement. In this case, we want to insert our counter right after&amp;nbsp;the
opening heading tag. We can match that exact position like&amp;nbsp;so:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;/\v\&amp;lt;h3\&amp;gt;\zs/
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;We have to escape the &lt;code&gt;&amp;lt;&lt;/code&gt; and &lt;code&gt;&amp;gt;&lt;/code&gt; because in Vim’s regular expression&amp;nbsp;syntax
they represent &lt;a href="http://vimdoc.sourceforge.net/htmldoc/pattern.html#/\&amp;lt;"&gt;left en right word boundaries&lt;/a&gt;. &lt;code&gt;\zs&lt;/code&gt; is&amp;nbsp;Vim’s
&lt;a href="http://vimdoc.sourceforge.net/htmldoc/pattern.html#/\zs"&gt;positive look-behind&lt;/a&gt; syntax, causing Vim to look for our opening&amp;nbsp;heading
tag, but only starting our match &lt;em&gt;after&lt;/em&gt;&amp;nbsp;it.&lt;/p&gt;

&lt;p&gt;Using vimscript to increment a counter is not too hard, either. We could do&amp;nbsp;it
like&amp;nbsp;so:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;let i=1
" insert i in the document somehow
let i=i+1
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;My first try to combine these was to just use a regular substitue&amp;nbsp;command,
combining it with the vimscript lines for the&amp;nbsp;counter:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;:let i=1 | %s/\v\&amp;lt;h3\&amp;gt;\zs/\=i/ | let i=i+1
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;You can use &lt;code&gt;|&lt;/code&gt; to combine multiple statements into a single command.&amp;nbsp;&lt;code&gt;\=i&lt;/code&gt;
will use the current value of &lt;code&gt;i&lt;/code&gt; as the the substituion string. But here’s&amp;nbsp;the
end&amp;nbsp;result:&lt;/p&gt;

&lt;pre lang="html"&gt;&lt;code&gt;&amp;lt;h3&amp;gt;1Heading 1&amp;lt;/h3&amp;gt;
&amp;lt;p&amp;gt;Lorem ipsum&amp;lt;/p&amp;gt;
&amp;lt;h3&amp;gt;1Heading 2&amp;lt;/h3&amp;gt;
&amp;lt;p&amp;gt;Lorem ipsum&amp;lt;/p&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Vim has inserted the same value of &lt;code&gt;i&lt;/code&gt; on every match. Here’s why: &lt;code&gt;%s&lt;/code&gt; is&amp;nbsp;a
&lt;em&gt;single&lt;/em&gt; operation on a range (&lt;code&gt;%&lt;/code&gt;) that includes the entire document. If&amp;nbsp;only
we could make a single replacement for every line that matched our search…&amp;nbsp;The
global command to the rescue,&amp;nbsp;again:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;:let i=1 | g/\v\&amp;lt;h3\&amp;gt;\zs/s//\=i/ | let i=i+1
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;I replaced the &lt;code&gt;%&lt;/code&gt; range with a global command using the same search&amp;nbsp;pattern.
To not repeat myself, I removed the search pattern from the&amp;nbsp;substitution
command, causing vim to re-use to last used pattern – which in this case&amp;nbsp;is
the pattern from the global command. Miraculously, it&amp;nbsp;works:&lt;/p&gt;

&lt;pre lang="html"&gt;&lt;code&gt;&amp;lt;h3&amp;gt;1Heading 1&amp;lt;/h3&amp;gt;
&amp;lt;p&amp;gt;Lorem ipsum&amp;lt;/p&amp;gt;
&amp;lt;h3&amp;gt;2Heading 2&amp;lt;/h3&amp;gt;
&amp;lt;p&amp;gt;Lorem ipsum&amp;lt;/p&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;We just need to add a little extra text to the substitution&amp;nbsp;string:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;:let i=1 | g/\v\&amp;lt;h3\&amp;gt;\zs/s//\=i.". "/ | let i=i+1
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;As you can see, we can concatenate the string &lt;code&gt;". "&lt;/code&gt; to our counter using&amp;nbsp;the
&lt;code&gt;.&lt;/code&gt; operator, giving us the end&amp;nbsp;result:&lt;/p&gt;

&lt;pre lang="html"&gt;&lt;code&gt;&amp;lt;h3&amp;gt;1. Heading 1&amp;lt;/h3&amp;gt;
&amp;lt;p&amp;gt;Lorem ipsum&amp;lt;/p&amp;gt;
&amp;lt;h3&amp;gt;2. Heading 2&amp;lt;/h3&amp;gt;
&amp;lt;p&amp;gt;Lorem ipsum&amp;lt;/p&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Another great&amp;nbsp;success!&lt;/p&gt;

&lt;h2&gt;4. Editing complex&amp;nbsp;commands&lt;/h2&gt;

&lt;p&gt;Admittedly, we have created quite a monster command using vimscript, a&amp;nbsp;global
command, a substition command, the special expression register and&amp;nbsp;positive
look-behinds. But Vim is a developer’s editor, and developers (should)&amp;nbsp;know
this stuff. It is not the most readable of code, but it is not horrible&amp;nbsp;either.&lt;/p&gt;

&lt;p&gt;The only truly awkward aspect of typing complex commands like these is&amp;nbsp;entering
them on Vim’s command line. There’s a remedy for that, though: the &lt;a href="http://vimdoc.sourceforge.net/htmldoc/cmdline.html#command-line-window"&gt;command
line window&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;The command line window is a new window (a split screen) in the current&amp;nbsp;tab,
that contains a buffer with your entire command history, one command per&amp;nbsp;line.
You can move around and edit commands just like in any buffer, making it&amp;nbsp;easy
to make changes. But when you press &lt;code&gt;Enter&lt;/code&gt; in normal mode, it will execute&amp;nbsp;the
current line as if you had typed it on Vim’s command line, against&amp;nbsp;the
previously active&amp;nbsp;window.&lt;/p&gt;

&lt;p&gt;The command line window is a great help in iteratively building up&amp;nbsp;complex
commands. It allows you to quickly revisit previously issued commands,&amp;nbsp;make
some changes, and execute it again. When done, you can simply close it&amp;nbsp;again
using &lt;code&gt;:q&lt;/code&gt;. But Vim wouldn’t be Vim if it hadn’t some awkardness, and this&amp;nbsp;time
it’s the &lt;code&gt;q:&lt;/code&gt; shortcut to open it. It just way too similar to &lt;code&gt;:q&lt;/code&gt;, and I&amp;nbsp;open
the command-line window by accident &lt;em&gt;all the time&lt;/em&gt;.&lt;/p&gt;

&lt;div class="footnotes"&gt;
  &lt;ol&gt;
    &lt;li id="fn:1"&gt;
      &lt;p&gt;For a full list of available ex commands, search the Vim help system using: &lt;code&gt;:help holy-grail&lt;/code&gt;.&lt;a href="#fnref:1" rel="reference"&gt;&amp;#8617;&lt;/a&gt;&lt;/p&gt;
    &lt;/li&gt;
  &lt;/ol&gt;
&lt;/div&gt;
</content>
  </entry>
  <entry>
    <id>tag:arjanvandergaag.nl,2012-06-20:/blog/factory_girl_tips.html</id>
    <title type="html">FactoryGirl Tips and Tricks</title>
    <published>2012-06-20T19:00:00Z</published>
    <updated>2012-06-20T19:00:00Z</updated>
    <link rel="alternate" href="http://arjanvandergaag.nl/blog/factory_girl_tips.html"/>
    <content type="html">&lt;p class="leader"&gt;&lt;a href="https://github.com/thoughtbot/factory_girl"&gt;FactoryGirl&lt;/a&gt; is an awesome fixture replacement library that gives you a&amp;nbsp;lot
of power and flexibility, at the cost of more code to maintain and&amp;nbsp;increased
mental overhead. It pays get to know it, so you can wield its flexibility&amp;nbsp;to
improve your tests and your&amp;nbsp;productivity.&lt;/p&gt;

&lt;h2&gt;Get the most out of&amp;nbsp;FactoryGirl&lt;/h2&gt;

&lt;h3&gt;1. Use &lt;strong&gt;traits&lt;/strong&gt; for modular&amp;nbsp;factories&lt;/h3&gt;

&lt;p&gt;Traits are reusable pieces of attribute definitions that you can mix and&amp;nbsp;match
into your factories. Traits are to factories what modules are to classes a&amp;nbsp;much
more natural and flexible way of sharing common&amp;nbsp;behaviour.&lt;/p&gt;

&lt;p&gt;For example, say you have a &lt;code&gt;Post&lt;/code&gt; and a &lt;code&gt;Page&lt;/code&gt; object that both have&amp;nbsp;a
publication date. You could use inheritance to create various&amp;nbsp;combinations:&lt;/p&gt;

&lt;pre lang="ruby"&gt;&lt;code&gt;FactoryGirl.define do
  factory :post do
    title 'New post'

    factory :draft_post do
      published_at nil
    end

    factory :published_post do
      published_at Date.new(2012, 12, 3)
        end
      end

  factory :page do
    title 'New page'
    
    factory :draft_page do
      published_at nil
    end

    factory :published_page do
      published_at Date.new(2012, 12, 3)
    end
  end
end

FactoryGirl.create :draft_page
FactoryGirl.create :published_post
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The repetition should be obvious. Traits can make this&amp;nbsp;&lt;span class="caps"&gt;DRY&lt;/span&gt;:&lt;/p&gt;

&lt;pre lang="ruby"&gt;&lt;code&gt;FactoryGirl.define do
  factory :post do
    title 'New post'
  end

  factory :page do
    title 'New page'
  end

  trait :published do
    published_at Date.new(2012, 12, 3)
  end

  trait :draft do
    published_at nil
  end
end

FactoryGirl.create :post, :published
FactoryGirl.create :page, :draft
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;With a simple example the difference might seem trivial, but try to think&amp;nbsp;how
quickly the complexity of your inheritance chain would increase if you had&amp;nbsp;not
one but two, six or twelve different attributes (or sets of attributes)&amp;nbsp;you
wanted to be able to apply in different&amp;nbsp;combinations.&lt;/p&gt;

&lt;p&gt;Traits are awesome because they can define callbacks, ignored attributes&amp;nbsp;and
even nest other&amp;nbsp;traits.&lt;/p&gt;

&lt;h3&gt;2. Use ignored attributes to tweak&amp;nbsp;callbacks&lt;/h3&gt;

&lt;p&gt;FactoryGirl lets you define ignored attributes, which will not be set on&amp;nbsp;your
newly created object. This is surprisingly useful in combination with&amp;nbsp;dependent
attributes and callbacks, which do get to access&amp;nbsp;them.&lt;/p&gt;

&lt;p&gt;Consider an example of a blog post with&amp;nbsp;comments:&lt;/p&gt;

&lt;pre lang="ruby"&gt;&lt;code&gt;FactoryGirl.define do
  factory :comment do
    author 'Anonymous'
    body 'Great post, man!'
    approved_at Date.new(2012, 3, 6)
    post
  end

  factory :post do
    title 'New post'
  end

  trait :with_comments do
    after :create do |post|
      FactoryGirl.create_list :comment, 3, :post =&amp;gt; post
    end
  end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;It is trivial to create a post with three comments by applying&amp;nbsp;the
&lt;code&gt;with_comments&lt;/code&gt; trait to a factory invocation. But what if we wanted to&amp;nbsp;adjust
the number of comments? We can use an ignored&amp;nbsp;attribute:&lt;/p&gt;

&lt;pre lang="ruby"&gt;&lt;code&gt;trait :with_comments do
  ignore do
    number_of_comments 3
  end
  
  after :create do |post, evaluator|
    FactoryGirl.create_list :comment, evaluator.number_of_comments, :post =&amp;gt; post
  end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Note that a special second argument is passed to the callback block,&amp;nbsp;the
evaluator, which knows about the ignored attributes. Now you can simply pass&amp;nbsp;in
the ignored attribute like you do a regular&amp;nbsp;attribute:&lt;/p&gt;

&lt;pre lang="ruby"&gt;&lt;code&gt;FactoryGirl.create :post, :with_comments, :number_of_comments =&amp;gt; 4
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Make trivial variations possible with ignored attributes removes the need&amp;nbsp;for
tons of almost-identical&amp;nbsp;factories.&lt;/p&gt;

&lt;h3&gt;3. Create non-generic&amp;nbsp;examples&lt;/h3&gt;

&lt;p&gt;Your factories are used in tests with as goal to make assertions about&amp;nbsp;their
state and behaviour. It can really help to use very specific example&amp;nbsp;objects
with well-known attribute values. So don’t create&amp;nbsp;a
&lt;code&gt;person_with_three_comments_and_a_post&lt;/code&gt;; instead use a &lt;code&gt;person_mike&lt;/code&gt;&amp;nbsp;and
&lt;code&gt;person_john&lt;/code&gt;. Use your factories to let your tests tell a simple story&amp;nbsp;about
your&amp;nbsp;objects.&lt;/p&gt;

&lt;h3&gt;4. Use&amp;nbsp;aliases&lt;/h3&gt;

&lt;p&gt;FactoryGirl allows you to define aliases to existing factories to make&amp;nbsp;them
easier to re-use. This could come in handy when, for example, your&amp;nbsp;&lt;code&gt;Post&lt;/code&gt;
object has a &lt;code&gt;author&lt;/code&gt; attribute that actually refers to an instance of a&amp;nbsp;&lt;code&gt;User&lt;/code&gt;
class. While normally FactoryGirl can infer the factory name from&amp;nbsp;the
association name, in this case it will look for a &lt;code&gt;author&lt;/code&gt; factory in vain.&amp;nbsp;So,
alias your &lt;code&gt;user&lt;/code&gt;&amp;nbsp;factory:&lt;/p&gt;

&lt;pre lang="ruby"&gt;&lt;code&gt;FactoryGirl.define do
  factory :user, :aliases =&amp;gt; [:author] do
    username 'anonymous'
  end

  factory :post do
    author # =&amp;gt; populated with the user factory
  end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;h3&gt;5. allow setting up common&amp;nbsp;associations&lt;/h3&gt;

&lt;p&gt;When you have many business models with many associations to other&amp;nbsp;business
models, you quickly end up with tests that first have to employ a dozen&amp;nbsp;objects
before the object under test is in such a state that meaningful queries can&amp;nbsp;be
made about it. This might be a sign of bad design, but could very well&amp;nbsp;be
unavoidable. In case of the latter, consider creating traits and factories&amp;nbsp;that
preload such associations for you, as with the example of a post with&amp;nbsp;comments:&lt;/p&gt;

&lt;pre lang="ruby"&gt;&lt;code&gt;FactoryGirl.define do
  factory :post do
    title 'New post'
  end

  trait :with_comments do
    after :create do |post|
      FactoryGirl.create_list :comment, 3, :post =&amp;gt; post
    end
  end
end

FactoryGirl.create :post, :with_comments
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Common pitfalls when creating&amp;nbsp;factories&lt;/h2&gt;

&lt;h3&gt;1. Do not use random attribute&amp;nbsp;values&lt;/h3&gt;

&lt;p&gt;One common pattern is to use a fake data library (like &lt;a href="http://faker.rubyforge.org/"&gt;Faker&lt;/a&gt;&amp;nbsp;or
&lt;a href="https://github.com/sevenwire/forgery"&gt;Forgery&lt;/a&gt;) to generate random values on the fly. This may seem&amp;nbsp;attractive
for names, email addresses or telephone numbers, but it serves no real&amp;nbsp;purpose.
Creating unique values is simple enough with&amp;nbsp;sequences:&lt;/p&gt;

&lt;pre lang="ruby"&gt;&lt;code&gt;FactoryGirl.define do
  sequence(:title) { |n| "Example title #{n}" }

  factory :post do
    title
  end
end

FactoryGirl.create(:post).title # =&amp;gt; 'Example title 1'
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Your randomised data might at some stage trigger unexpected results in&amp;nbsp;your
tests, making your factories frustrating to work with. Any value that might&amp;nbsp;affect
your test outcome in some way would have to be overridden,&amp;nbsp;meaning:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Over time, you will discover new attributes that cause your test to&amp;nbsp;fail
sometimes. This is a frustrating process, since tests might fail only&amp;nbsp;once
in every ten or hundred runs – depending on how many attributes&amp;nbsp;and
possible values there are, and which combination triggers the&amp;nbsp;bug.&lt;/li&gt;
  &lt;li&gt;You will have to list every such random attribute in every test to&amp;nbsp;override
it, which is silly. So, you create non-random factories, thereby&amp;nbsp;negating
any benefit of the original&amp;nbsp;randomness.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;One might argue, &lt;a href="http://henrik.nyh.se/2012/07/randomize-your-factories"&gt;as Henrik Nyh does&lt;/a&gt;, that random values help you&amp;nbsp;discover
bugs. While possible, that obviously means you have a bigger problem: holes&amp;nbsp;in
your test suite. In the worst case scenario the bug &lt;em&gt;still&lt;/em&gt; goes undetected;&amp;nbsp;in
the best case scenario you get a cryptic error message that disappears the&amp;nbsp;next
time you run the test, making it hard to debug. True, a cryptic error is&amp;nbsp;better
than no error, but randomised factories remain a poor substitute for&amp;nbsp;proper
unit tests, code review and &lt;span class="caps"&gt;TDD&lt;/span&gt; to prevent these&amp;nbsp;problems.&lt;/p&gt;

&lt;p&gt;Randomised factories are therefore not only not worth the effort, they&amp;nbsp;even
give you false confidence in your tests, which is worse than having no tests&amp;nbsp;at
all.&lt;/p&gt;

&lt;h3&gt;2. Test for explicit&amp;nbsp;values&lt;/h3&gt;

&lt;p&gt;In addition to random values being bad, relying on your factories&amp;nbsp;default
values may be bad idea, too. Unless you create specific&amp;nbsp;story-telling
factories, such as “john” rather than “user1”, you should anticipate&amp;nbsp;someone
else (i.e. you, four weeks from now) changing the default factory values.&amp;nbsp;When
you are testing, you want to test for explicit values your test controls.&amp;nbsp;A
test like this is&amp;nbsp;silly:&lt;/p&gt;

&lt;pre lang="ruby"&gt;&lt;code&gt;FactoryGirl.define do
  factory :post do
    title { Forgery(:lorem_ipsum).words(5) }
  end
end

describe 'Blog' do
  it 'should show the post title on the page' do
    post = FactoryGirl.create :post
    visit '/blog'
    page.should have_content(post.title)
  end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;What happens when your post title randomly turns out to be an empty string,&amp;nbsp;or
a phrase that also happens to occur somewhere else on the page? If your&amp;nbsp;test
value is random or outside your control, how can you prove something about&amp;nbsp;it?
Consider this improved example and its increased&amp;nbsp;readability:&lt;/p&gt;

&lt;pre lang="ruby"&gt;&lt;code&gt;it 'should show the post title on the page' do
  post = FactoryGirl.create :post, :title =&amp;gt; 'My example post'
  visit '/blog'
  page.should have_content('My example post')
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The explicit title and test value underline the intent of the test and&amp;nbsp;leave
far less room for false positives or future&amp;nbsp;changes.&lt;/p&gt;

&lt;h3&gt;3. Do not use dynamic values by&amp;nbsp;default&lt;/h3&gt;

&lt;p&gt;Dynamic attribute values are evaluated on invocation time rather&amp;nbsp;than
evaluation time. This allows you to use, for example, the current time in&amp;nbsp;your
factories:&lt;/p&gt;

&lt;pre lang="ruby"&gt;&lt;code&gt;FactoryGirl.define do
  factory :post do
    created_at Time.now # =&amp;gt; will be the same for every object
    published_at { Time.now } # =&amp;gt; will be updated for every object
  end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This does not mean, however, that you should alway use dynamic attribute&amp;nbsp;values
when a simple static value will do&amp;nbsp;fine:&lt;/p&gt;

&lt;pre lang="ruby"&gt;&lt;code&gt;FactoryGirl.define do
  factory :post do
    title { 'My new post' } # silly!
    body 'Lorem ipsum'      # pretty!
  end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Although I’m sure there will be minor performance benefits to using&amp;nbsp;static
values, that is not the point. We want our tests to be readable and&amp;nbsp;clear.
Using blocks everywhere conceals the true meaning of the actually&amp;nbsp;dynamic
attributes between the static&amp;nbsp;attributes.&lt;/p&gt;

&lt;h3&gt;4. Do not manually create&amp;nbsp;associations&lt;/h3&gt;

&lt;p&gt;When using Rails, FactoryGirl is smart enough to know how to set&amp;nbsp;up
associations for you. So don’t do&amp;nbsp;this:&lt;/p&gt;

&lt;pre lang="ruby"&gt;&lt;code&gt;FactoryGirl.define do
  factory :comment do
    post { FactoryGirl.create :post }
  end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Usually you can just use another factory name as an attribute, or use&amp;nbsp;the
&lt;code&gt;association&lt;/code&gt; method to customise&amp;nbsp;it:&lt;/p&gt;

&lt;pre lang="ruby"&gt;&lt;code&gt;FactoryGirl.define do
  factory :comment do
    post
  end

  factory :user do
    username 'anonymous'
  end

  factory :post do
    association :author, :factory =&amp;gt; :user, :username =&amp;gt; 'admin'
  end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Note how the &lt;code&gt;comment&lt;/code&gt; factory simply uses the &lt;code&gt;post&lt;/code&gt; factory to set its&amp;nbsp;&lt;code&gt;post&lt;/code&gt;
attribute. The &lt;code&gt;post&lt;/code&gt; factory however uses the &lt;code&gt;user&lt;/code&gt; factory to populate&amp;nbsp;its
&lt;code&gt;author&lt;/code&gt; attribute &lt;em&gt;and&lt;/em&gt; provides some additional details on how it is to&amp;nbsp;be
built.&lt;/p&gt;

&lt;h2&gt;Further&amp;nbsp;reading&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Henrik Nyh believes you should &lt;a href="http://henrik.nyh.se/2012/07/randomize-your-factories"&gt;randomize your&amp;nbsp;factories&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href="http://robots.thoughtbot.com/post/21719164760/factorygirl-3-2-so-awesome-it-needs-to-be-released"&gt;New features in FactoryGirl &lt;span class="caps"&gt;3.2&lt;/span&gt;&lt;/a&gt; by Thoughtbot, including custom build strategies and callback&amp;nbsp;skipping.&lt;/li&gt;
  &lt;li&gt;Thoughbot recommends you &lt;a href="http://robots.thoughtbot.com/post/22670085288/use-factory-girls-build-stubbed-for-a-faster-test"&gt;use &lt;code&gt;build_stubbed&lt;/code&gt; for a faster test&amp;nbsp;suite&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;More&amp;nbsp;tips?&lt;/h2&gt;

&lt;p&gt;If you have any pet peeves when using FactoryGirl, &lt;a href="http://twitter.com/avdgaag"&gt;let me know on Twitter&lt;/a&gt;!&lt;/p&gt;

</content>
  </entry>
</feed>

