@awead

Technical notes and explications of code

Grammar

It goes without saying, grammar counts. Take for example:

1
2
3
def display_message(msg)
  putt msg
end

Trying to use this:

> display_message("Hi!")
NoMethodError: undefined method `putt' for main:Object`

Programming languages loudly complain when we make grammatical, syntactical, or any other kind of -icle errors. But taking another example:

1
2
3
4
# Useing a putt to printing message
def display_message(msg)
  puts msg
end

Ruby’s totally fine with that. Too bad, I’m not. It would be nice if programming languages took the same approach to its own grammar as it did with other languages’ grammar. In my opinion, grammar counts in all languages, be it Ruby, Haskell, English or Dutch.

We as programmers can enable spell-check features in our editors, but that still puts in onus on us and even with that, it still compiles. Perhaps a rubocop extension that could fail your PRs for bad grammar or spelling? It’s easier said than done because an incorrect method name is definitive, whereas the Oxford comma is a little less so.

We don’t have to get into that level of enforcement, but the end result should be that comments or other non-code should be held to the same exacting standards as the actual code. Right now that’s on us. Just saying let’s all be more vigilant. After all, you never know who will be reading your comments!

Commutative Multiplication in Ruby

I discovered this today while working through the roman numerals kata on exercism.io: Multiplication of strings in Ruby is not commutative.

Huh?

Yeah, I had to look it up too. In math, the “Commutative Property for Multiplication” states that for any two real numbers a and b:

a * b = b * a

In Ruby, you can do strange things with multiplication like:

1
2
>  "a" * 2
=> "aa"

But the commutative property does not hold in this case:

1
2
>  2 * "a"
*** TypeError Exception: String can't be coerced into Fixnum

If you think about it for a second, it makes sense, but you have to say it to yourself. First, “A times 2” kinds sounds reasonable. In other words, take “a” and do it twice. However, saying “2 times a” sounds odd because you immediately have to ask yourself, “What is ‘a’?”

Ruby ask itself the same question and decides that if the first thing I’m multiplying is a Fixnum, then the next thing has to be a Fixnum as well, and if it’s not, I’ll try to make it one. Therein lies the problem: ‘a’ can’t be made into a Fixnum. The strangeness or ‘magic’ is when it’s the other way around, and Ruby can deduce that it should just repeat strings when multiplied by numbers instead of attempting to do the reverse of what it did before, and coerce the string into a number.

Oddly, none of this works with addition:

1
2
3
4
5
> "a" + 2
*** TypeError Exception: no implicit conversion of Fixnum into String

> 2 + "a"
*** TypeError Exception: String can't be coerced into Fixnum

If you can multiple strings by number, one might reasonably assume that adding them would produce something like:

"a" + 2 = "a2"
2 + "a" = "2a"

Alas, the magic stops there.

(Yet Another Post About) Presenters in Rails

YAPAPIR! Lots of virtual ink has been spilled over presenters in Rails. My take on them that follows came about after our team decided to arrive at an adoption strategy. We’d been using them in other projects, and were starting to go down a road of implementing them different ways, when we though we should pick one way and stick to it.

Here’s a summary of what I’ve found are the different ways you can do presenters and I’ll conclude with the way I think they ought to be done.

They’re Really Decorators

If you read about presenters, you’ll probably see them side-by-side with references to decorators. According to wikipedia: [1]

In object-oriented programming, the decorator pattern (also known as Wrapper, an alternative naming shared with the Adapter pattern) is a design pattern that allows behavior to be added to an individual object, either statically or dynamically, without affecting the behavior of other objects from the same class.

Presenters are going to do something with your model, usually an ActiveRecord object, and do something with it that will modify it, yet leave it intact in its original state. The best use case would be display logic such as someone’s name.

1
2
3
4
5
6
7
class Person < ActiveRecord::Base
  attr_acessor :first_name, :last_name, :salutation

  def full_name
    [salutation, first_name, last_name].join(" ")
  end
end

full_name doesn’t really have any bearing on the Person data model, it’s purely for display. A while back, I probably would have put this in a helper. However, the helper doesn’t really know anything about Person, and you’d have to make some assumptions about how your controller might be instantiating Person:

1
2
3
4
5
module PersonHelper
  def full_name
    [@person.salutation, @person.first_name, @person.last_name].join(" ")
  end
end

What if @person is nil? What if salutation is nil? So a simple display method can quickly morph into a complex logic problem. Enter the presenter: put all that logic and code in another class separate from the model.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class PersonPresenter
  delegate :first_name, :last_name, to: :model

  attr_reader :model

  def initialize(model)
    @model = model
  end

  def full_name
    [salutation, first_name, last_name].join(" ")
  end

  def salutation
    model.salutation || inferred_salutation
  end

  private

    # Let's assume that ::gender is a required attribute
    def inferred_salutation
      if model.gender == "male"
        "Mr."
      else
        "Ms."
      end
    end
end

In that brief example above, I’ve already made a bunch of assumptions about how I’m going to build my presenters, but there are many ways I could have implemented the above solution. Let’s look into them.

The Approaches

The Model Presenter

  • instantiated by the controller, helper, or view
  • operates on only one model
  • initialized with an instance of the model it’s presenting

The Assembler

  • instantiated by the controller
  • assembles access to multiple models within one controller

The Templative Presenter

  • uses either of above strategies
  • adds the current ActionView::Context as a second parameter

Guidelines

Requirements

I’ll start with Sandi Metz’s rules which cover more than just presenters, except the last one:

  • Classes can be no longer than one hundred lines of code.
  • Methods can be no longer than five lines of code.
  • Pass no more than four parameters into a method. Hash options are parameters.
  • Controllers can instantiate only one object.

So basically, if you’re using presenters, your controllers can only do one thing: instantiate a presenter. This might seem a bit draconian, but there’s an advantage here. Have you ever dealt with a controller that’s doing so much stuff you don’t know where what’s getting done where? Well, if your controller can only do one thing, then it kinda solves that problem for you.

You can break these rules if you absolutely have to, but the idea is that because these limits are there it informs you as to the complexity of your methods and classes. In other words, if you have a class with more that 100 lines, maybe there’s underlying cause that should be addressed instead of just plowing ahead with a really big class. On the other hand, if you’ve thought it through and can make a well-thought case for a long class, you’re free to have one.

Very Strong Recommendations

Use POROs

Ruby has a enough built-in features to cover the use cases, which makes additional tooling, while neat, magical, and cool, ultimately superfluous. That isn’t to say you can’t use them. However, there’s enough in the stock Ruby toolbag to fix any problem

  • object-oriented design through composition or inheritance
  • modules
  • delegation methods
  • judicious use of monkeypatching as a last resort

Use POR (plain old Rails)

Rails has views to render HTML. Use them for that. Partials can subdivide this HTML layer into logical units that fit your use case or design rules. Rails has helpers, and no, they’re not evil. Use them, appropriately, particularly for specific cases that cut across multiple presenters and do not depend on a data conditional in your model.

A view should only use one presenter

If you have a view that needs more that one presenter, you have a presenter problem. You can build another presenter. If you have a lot of presenters, think about strategies like inheritance or composition in order to DRY up your presenters. If you’re finding that it’s difficult to construct a single presenter for a view, maybe that’s an indication that the view itself is too complicated and needs some refactoring.

Meh

Only instantiate your presenters in controllers/views/helpers

While I feel awkward when I instantiate anything in view or helper, I can’t really find a coherent argument as to why it’s a bad idea. So, feel free to instantiate your presenters anywhere, but I still think there should be one presenter per view, or view partial.

Presenters should not contain HTML

Probably, yes, but there could be reasons for it such as sharing a display behavior across presenters, but helpers are a better fit there perhaps?

Views should not contain logic

Ideally, maybe. Practically, though, a small amount of logic doesn’t seem to disrupt things:

1
2
3
<h1>User Information</h1>
<p>Hello, <%= presenter.first_name %></p>
<%= render "activity" if presenter.has_activity? %>

Iterators present their own problems, but shouldn’t be too disruptive either:

1
2
3
4
5
6
7
<h2>Recent Activity</h2>
<table>
<tr><th>Date</th><th>Action</th></tr>
<% presenter.user_activity.each do |activity| %>
  <tr><td><%= activity.date %></td><td><%= activity.action %></td></tr>
<% end %>
</table>

Or if you want to unify all your table displays, consider some helpers:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
module TabularHelpers

  def header_row(*cols)
    content_tag :tr do
      cols.map |col| {  |col| content_tag :th, col, class: "my-header-class" }
    end
  end

  def table_row(*cols)
    content_tag :tr do
      cols.map |col| {  |col| content_tag :td, col, class: "my-row-class" }
    end
  end
end

Then your table views become more reusable:

1
2
3
4
5
<h2>Recent Activity</h2>
<table>
  <%= header_row("Date", "Action")
  <%= presenter.user_activity.map { |activity| table_row(activity.date, activity.action) } %>
</table>

Tools

Draper

Gem on github. Instantiates a decorator based on your ActiveRecord model. There’s some good discussion about its pros and cons

Curly

Gem on github Rails meets handlebars.js

Notes

[1] https://en.wikipedia.org/wiki/Decorator_pattern

References

Corbel, Guirec, “When I use Helpers, Partials, Presenters and Decorators,” July 2013, https://coderwall.com/p/jx9tca/when-i-use-helpers-partials-presenters-and-decorators

Fields, Jay, “Rails: Presenter Pattern,” 9/16/2007, http://blog.jayfields.com/2007/03/rails-presenter-pattern.html

Fowler, Martin, “Presentation Model,” 7/19/2004, http://martinfowler.com/eaaDev/PresentationModel.html

Goswami, Mainak, “Gang of Four – Decorate with Decorator Design Pattern,” https://dzone.com/articles/gang-four-%E2%80%93-decorate-decorator

Hock-Isaza, “Mixing Presenters and Helper,” http://blog.nhocki.com/2012/05/08/mixing-presenters-and-helpers/

Murray, Robert, “Decorators, Presenters, Delegators and Rails,” 1/23/2014, https://robertomurray.co.uk/blog/2014/decorators-presenters-delegators-rails/

Seitz, Jeremy, “Thoughts about Rails Presenters,” https://gist.github.com/somebox/5a7ebf56e3236372eec4

Vlasveld, Roemer, “http://www.inspire.nl/blog/rails-presenters-filling-the-model-view-controller-gap/

Wang, Eugene, “Presenting the Rails Presenter Pattern,” 9/26/2013, http://eewang.github.io/blog/2013/09/26/presenting-the-rails-presenter-pattern/

Rebuilding Your Github Pages Site

This happens to me a lot because I go so long without writing a post. By the time I’ve gotten around to writing something, I’ve had my laptop reimaged, or I’ve deleted the repo. So I end up having to recreate the entire Github pages setup… and I don’t remember how!

To my future, befuddled self, please take heed:

1
2
3
4
5
6
git clone $GITHUB_PAGES_REPO gp
cd gp
git checkout source
bundle update
git clone $GITHUB_PAGES_REPO _deploy
bundle exec rake gen_deploy

You can even cut and paste. Trust me! This is yourself you’re talking to.

HTTP Headers With Capybara’s Drivers

I stumbled across this very slight but significant difference when trying to inject some HTTP headers into an application being tested with Capybara.

If you’re running a server-side authentication scheme such as LDAP or Shibboleth, you can rely on server variables to get the name of the person who’s authenticated to use your application. Usually it’s a variable like “REMOTE_USER” or something else. When you’re testing, you’ll want your test app to add that variable to the server’s headers.

Using Capybara::RackTest::Driver, this looks something like:

1
2
3
4
5
Capybara.register_driver(:driver_name) do |app|
  Capybara::RackTest::Driver.new(app,
                                 respect_data_method: true,
                                 headers: { 'HTTP_REMOTE_USER' => 'joe' })
end

And if we query the variable in our test:

>  request.env.fetch("HTTP_REMOTE_USER")
=> "joe"

Now let’s use the Capybara::Poltergeist::Driver instead so we can test some Javascript. At first, that looks like:

1
2
3
4
5
Capybara.register_driver(:poltergeist) do |app|
  driver = Capybara::Poltergeist::Driver.new(app, js_errors: true, timeout: 90)
  driver.headers = { 'HTTP_REMOTE_USER' => 'joe' }
  driver
end

But look what happens to our ENV hash:

>  request.env
=> {"HTTP_HTTP_REMOTE_USER"=>"joe"}

The Poltergeist driver is appending another HTTP_ on to the variable. I don’t have a definitive explanation, but I suspect this is because of a section of the CGI specification rfc3875 that dictates how variables sent from the client are inpreted by the server.

The gist is, since Poltergeist is a more fully-fledged client/server setup, it’s going to do the variable conversion for you, whereas the RackTest driver doesn’t and you have to do it yourself.

In any case, to fix the above problem, just don’t add the “HTTP” prefix to the variable if you’re using Poltergeist.

Capistrano

I’ve been working recently on a side project with a very restrictive server environment. Capistrano has turned out to be a good way to deploy news apps easily and quickly. Admittedly, I have a bit of a love/hate relationship with Cap. I use it at work, and it’s wonderful when it works… until it doesn’t, and then it becomes very frustrating. Part of this was was due to the fact that it was setup before I came on to my current job, so I didn’t see it getting built from the ground up. So I figured with this side project I could set it up myself and see better how it works.

I find that Capistrano adheres to Rails’ adage of “convention over configuration,” which is otherwise known as: magic. This means that a lot of things are being done automatically, and you don’t necessarily know how. In general, this is nice when you don’t care, but when comes to figuring out what’s wrong, that’s where the frustrations arise.

Setting up Capistrano initially is easy. I found several tutorials that were very helpful, including its own homepage:

Within no time, I was deploying with a one-liner from the command line; however, I got stuck. For some reason, assets weren’t being compiled nor were the database migrations being run. Under version 3, if you simply add this to your Capfile:

require 'capistrano/rails'

All of this is supposed to “magically” happen since the capistrano-rails gem includes all the tasks for performing database migrations and compiling assets. It does; and it will, provided you’ve defined the role for the server.

I missed that part. Roles are covered briefly, but the basic idea is that you may have your app deployed to different servers, one doing the app, one doing the database, and maybe another that’s the web front-end. Capistrano comes with roles already defined such as: web, db, and app.

If the server you’ve defined in the config/deploy directory isn’t assigned to a db role, then database migrations won’t occur — which makes complete sense of course, but it’s not immediately obvious. Similarly, you need to assign your server either the app or web role for assets as well.

config/deploy/test.rb
1
2
    server 'test.server.com', user: 'awead', roles: %w{web app db}

With the new configuration, everything went as expected.

Surveying the Javascript Landscape

Taking a break from my usual Ruby work, I did a “recovery sprint” and explored some Javascript. My skills are weak at best in this area and it was my intention to improve them by learning some new technologies.

Node.js

I’ve been hearing a lot about Node, and vaguely knew what I was. There’s a lot out there and even more about what you can do with it. In short, it’s a web application platform built on Chrome’s javascript runtime environment. It’s a single process application, which seems weird at first, but that’s the way it works and it work well.

There are tons of great tutorials on Node at Node School. The one I did was “learnyounode” which is a series of 13 exercises. It’s pretty simple, although I got annoyed a few times and grabbed the answers from learnyounode-solutions. Hey, I’m not getting graded on this or anything. It’s easy to get started:

brew install npm
npm install -g learnyounode
learnyounode

And you’re off and running. I posted my solutions as well if you’re intested. However, I didn’t go very deep into Node because I wanted to get a broader picture of the Javascript development landscape.

Express.js

Coming from a Rails background, I was more interested in how you can leverage Node to create web applications. This led me to Express.js which is pretty much exactly what a Rails developer might expect if they were looking for Node on “Rails.”

Express has an app generator that will build a complete application structure in a directory. From there, you can start the application and begin customizing routes and content. It features a routing mechanism and a template language called Jade, although you can supply others if you wish. In short, to start a new Express app:

npm install express
npm install express-generator -g
express my-app
cd my-app
npm install
npm start

It even starts up the webserver on the usual 3000 port. The similarities with Rails were actually a little eerie. Express isn’t a full MVC framework, though, it’s more like VC, or just V for that matter. As-is, Express gives you views and routes so it’s very easy to start creating simple static pages or pages that are transformed using JSON data objects.

For example, if I wanted to add a simple “About me” page to my base Express application, I create a route:

routes/about.js
1
2
3
4
5
6
7
8
9
var express = require('express');
var router = express.Router();

/* GET about page */
router.get('/', function(req, res, next) {
  res.render('about', { title: 'About' });
});

module.exports = router;

Because the route file is about.js it’s going to respond to GET requests at /about which is why the path is only “/” on line 5. After that, it’s just passing a JSON object to the view template, which looks like:

views/about.jade
1
2
3
4
5
extends layout

block content
  h1= title
  p About me

In order to have the page render, we’ll need to wire it up to our application. Add these lines in the relevant locations of your app.js file:

var about = require('./routes/about');

app.use('/about', about);

Now you can restart the server and view the page. Not much there, but you get the idea. I left it very basic because I was more intested in…

Testing

Coming from Rails, I’ve had TDD/BDD beaten into my head so it was very hard for me to doing anything without asking myself “Where is this tested?” To answer that, you have to look at some testing frameworks. I started with expect.js which has the syntax you might expect (heh) with Rspec. However, getting it wired up in Express required a few additional bits: Mocha and superagent. Expect.js provides the language for testing, Mocha provides the framework, which is a lot like Rspec and uses “it” and “describe” blocks. Superagent is a client-side HTTP request library that is making the actual calls to your app.

Here’s how I put it all together

npm install expect.js superagent
npm install -g mocha
mkdir test
mocha

After executing that last command, it will run mocha and report “0 passing” tests. So, let’s add one for our about page:

test/about.js
1
2
3
4
5
6
7
8
9
10
11
12
13
var expect = require('expect.js');
var request = require('superagent');

describe('the about page', function() {
  it('returns information about me', function(done) {
    request
      .get('/about')
      .end(function(err, res){
        expect(res.body).to.contain('About me');
      });
      done();
  });
});

Superagent makes the get request and using expect.js we can parse the body of the response for the expected content. Note: I was getting the warning “double callback!” which may be a bug, but I’m not sure. Everywhere on the net, this seems to be the accepted syntax, so take this for what it’s worth.

Jasmine

Another testing method is to use Jasmine which basically does the same as above, even with some of the same dependencies, but slightly differently. To setup, let use our package.json the way it’s meant to be and specify our dependencies. Add these lines to the dependencies key:

"jasmine-node": "~>1.14",
"request": "~2.56"

Then run:

npm install
jasmine init

Jasmine follows Rspec a little more closely and creates a spec directory and assumes you’ll name your tests with the _spec extension. To test our about page using Jasmine:

spec/about_spec.js
1
2
3
4
5
6
7
8
var request = require('request');

it("renders the about page", function(done) {
  request("http://localhost:3000/about", function(error, response, body){
    expect(body).toContain("About me");
    done();
  });
});

One thing to note, this test will only pass if your app.js is actually running. There are ways to wrap this so that Jasmine will start up the app first before testing.

M is for Model

The last bits to add into this mix are getting Express to model data in a ORM kind of way like Rails does. Again, there are lots to choose from here: Bookshelf, Backbone, Mongoose, Persistence, Sequelize, and the list goes on.

Many of these cater to one particular database, such as Mongoose connecting to MongoDB. There’s a specific platform that wraps these together: MEAN which stands for MongoDB, Express, Angular.js, and Node.js. It’s reminiscent of LAMP.

Backbone.js seems to be the most data agnostic, while others like Mongoose, focus on specific sources. For example, Sequelize does PostGRESql and MySQL.

Too Many Choices?

Angular.js is a popular choice as a fully-fledged MVC framework for Javascript, and it can be pulled into the mix in Express apps, as MEAN shows above. Lastly, Express isn’t the only choice for platforms. react.js is another “V” option in the MVC of the Javascript world.

RSpec: Testing Inputs

After trying to do this the other day, there are a lot of different approaches to doing this. Here’s mine:

Let’s say you have an edit form that has a text input with a value already entered into it.

1
<input name="name_field" value="Adam Wead" type="text" id="document[name_field]" />

You want to write a test that verifies if the content is already in the input field. Seems easy, but it turns out it’s not so. A lot of the answers out there resorted to using Xpath, which works fine, but you can leverage RSpec’s own finding tools to do this too:

1
expect(find_field("document[name_field]").value).to eql "Adam Wead"

It avoids XPath, if that’s not your thing, and it’s slightly easier to read. I would have expected (no pun intended) have_value to work, but it doesn’t look like it responds to has_value?.

Watching Your Test Application

When I run test with a sample Rails app, for example if I’m working on an engine gem, it’s sometimes difficult to see what’s going on if a test is failing. I’m a big proponent of having a clean database before every test. This means running a database cleaner and other tools that wipe out the data before and afterwards. This can present problems when you’re trying to nail down a particular failure because the data gets wiped after it’s over.

You can use tricks like the Byebug gem or calling save_and_open_page if you’re using Capybara, and these will often help. But, what if you want to open the actual test application at the exact moment prior to the failure? Here’s a trick I use:

Let’s say you’ve built-up a test rails application under spec/internal. This implies that you’re using RSpec, so if not, translate accordingly. Go into your test file and put in a byebug call right before the failure. The test will run and stop at the breakpoint. Leave the byebye prompt open and in another terminal:

$ cd spec/internal
$ bundle exec rails server -e test

ViolĂ . There’s your test application at exactly the point prior to the failure. Explore and poke around, but when you’re done, don’t forget to pop back over to the byebug prompt and enter:

(byebug) continue

The test will continue and so will the cleanup process. If you forget this, then the test application will not be a clean state the next time you run your tests.

Filters, Not Overrides

When refactoring some controllers, I realized it’s much nicer to filter actions on controllers instead of overriding them.

Take for example a controller that exists somewhere in your application or in a gem:

1
2
3
4
5
6
7
8
class BaseController < ApplicationController

  def index
    @terms = Terms.all
    render_all_terms
  end

end

I need to use that controller in my application, but have to add some additional stuff to it to use in my views:

1
2
3
4
5
6
7
8
9
10
class MyController < ApplicationController

  include BaseController

  def  index
    @my_terms = MyTerms.all
    super
  end

end

This will work and I’ll have both @terms and @my_terms in my views. However, I find it’s nicer, and a little bit less invasive, if I can work around BaseController without having override it:

1
2
3
4
5
6
7
8
9
10
11
class MyController < ApplicationController

  include BaseController

  before_filter :get_my_terms, only: :index

  def get_my_terms
    @my_terms = MyTerms.all
  end

end

The end result is the same, but I’ve accomplished it without having to change BaseController at all, thereby leaving its public interface untouched.