Jen Hamon

Rubyist and JavaScripter

Enforcing Your Template Pattern Interface With RSpec Shared Examples

The template pattern comes into play when you have several different use cases that are mostly the same but differ in just a few ways. Shared functionality and skeleton methods are defined in a base class, which will be overridden by each subclass. Each subclass provides a different implementation for the skeleton functions, and because all these objects all share a common interface we can use them interchangeably in other parts of our code.

Using class inheritance

The simplest way of implementing the template pattern is to define a base class that your various implementations inherit from and override. All of the methods we want included in the template subclasses must raise errors if not overridden. That way, if no implementation is present in a subclass we will see an error.

Take these printer classes for example.

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
29
30
31
class BasePrinter
  def prepare_and_print(data)
    print(magical_formatting(data))
  end

  def magical_formatting(data)
    "Magical data: #{data}"
  end

  def print(data)
    raise "Not implemented!"
  end
end

class PlainPrinter < BasePrinter
  def print(data)
    puts data
  end
end

class ShufflePrinter < BasePrinter
  def print(data)
    puts data.split("").shuffle.join
  end
end

class BogusPrinter < BasePrinter
  def bogus_print
    # whatever
  end
end

Now if we do BogusPrinter.new.prepare_and_print(data) we will see a “Not impelmented!” error because the expected print method was not defined in the subclass. A quick and easy fix.

This gets the job done, but doesn’t seem ideal. What if we want to make a printer class that writes data to a PDF file? We might need this class to inherit from another class providing complex PDF logic.

1
2
3
4
5
class PDFPrinter < BadassPDFLibrary
  def print(data)
    # do stuff
  end
end

Wrap the base template into a module

Ruby only has single inheritance, so there’s no way to subclass BasePrinter and BadassPDFLibrary. One way around the single-inheritance problem is to wrap up our BasePrinter into a module to be included.

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
module BasePrinter
  def prepare_and_print(data)
    print(magical_formatting(data))
  end

  def magical_formatting(data)
    "Magical data: #{data}"
  end

  def print(data)
    raise "not implemented"
  end
end

class PlainPrinter
  include BasePrinter

  def print(data)
    puts data
  end
end

class ShufflePrinter
  include BasePrinter

  def print(data)
    puts data.split("").shuffle.join
  end
end

class BogusPrinter
  include BasePrinter

  def bogus_print
    # whatever
  end
end

class PDFPrinter < BadassPDFLibrary
  include BasePrinter

  def print(data)
    # do stuff
  end
end

Leveraging RSpec shared_examples

Using modules is a perfectly workable solution if we need to inherit from a different class. But there’s a third way we can enforce our expectations on the printer interface. That is to write some shared examples for this code that check for the presence of the expected methods.

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
shared_examples "a printer class" do
  let(:printer) { described_class.new }

  it "should expose a #print method" do
    expect(printer).to respond_to(:print)
  end

  describe "#print" do
    it "should return nil" do
      expect(printer.print("Hello, World!")).to be_nil
    end
  end
end

printers = [
 PlainPrinter,
 BogusPrinter,
 ShufflePrinter,
 PDFPrinter
]

printers.each do |printer_class|
  describe printer_class do
    it_behaves_like "a printer class"
  end
end

This approach goes beyond the error-raising we get from the module or base class and allows us to make stipulations about the return values from each template method. With a few tests like this, we can dispense with the need for abstract base methods.

A Few Debugging Tips for the Rails Console

This post will be a little less coherent than some of the others, but I wanted to write down a few things I’ve found to be very helpful when trying to debug my Ruby code.

Quickly find syntax errors

A surprising number of people don’t know that you can run ruby with -c from the command line to learn about syntax errors. Let’s say I have a simple Dog class with an unclosed string.

1
2
3
4
5
6
7
8
9
10
11
# dog.rb
class Dog
  def initialize(name)
    @name = name
  end

  private
  def woof
    puts "woof
  end
end

This is a trivial example, but if I was having trouble tracking down the problem I’d do something like this:

1
2
3
$ ruby -c dog.rb
dog.rb:8: unterminated string meets end of file
dog.rb:8: syntax error, unexpected end-of-input, expecting keyword_end

Inspecting instance variables

From the console, we have the power to reach inside an object and see its instance variables even if there are no getter and setter methods defined on the object.

1
2
3
4
5
6
7
[2] pry(main)> d = Dog.new("Pluto")
=> #<Dog:0x007f82aac977d0 @name="Pluto">
[3] pry(main)> d.name
NoMethodError: undefined method `name' for #<Dog:0x007f82aac977d0 @name="Pluto">
from (pry):12:in `__pry__'
[4] pry(main)> d.instance_variable_get("@name")
=> "Pluto"

This slightly different syntax also works

1
2
[5] pry(main)> d.instance_variable_get(:@name)
=> "Pluto"

If we’re not sure what state the object is holding on to, we can get a list of all the defined instance variables using #instance_variables.

1
2
[6] pry(main)> d.instance_variables
=> [:@name]

Calling private methods

If you want to call a private method from the command line, you can do so with #send.

1
2
3
4
5
6
[7] pry(main)> d.woof
NoMethodError: private method `woof' called for #<Dog:0x007fd65acfe9b8 @name="Pluto">
from (pry):17:in `__pry__'
[8] pry(main)> d.send(:woof)
woof
=> nil

Discover where a method was defined

Sometimes, especially when working on a big application with other people, it’s tricky to learn where a particular method is defined. This is especially true when classes are being extended by gems that you did not write or install yourself.

To track those down, you can do this in the console.

1
instance.method(:method_name).source_location

For example, I might do something like this:

1
2
[25] pry(main)> Rails.method(:cache).source_location
=> ["/Users/jhamon/.rvm/gems/ruby-2.0.0-p247/gems/railties-4.1.4/lib/rails.rb", 32]

If the cache method had been overridden, as it sometimes is by gems like dalli_store, I would see a reference to that gem instead of rails.

Using JavaScript Animation to Communicate IFTTT at a Glance

See the Pen IFTTT Slottt Machine by Jennifer Hamon (@jhamon) on CodePen.

At IFTTT we’re always looking for better ways to communicate what our service is and how people can use us to connect the services they love together in powerful ways. One idea I had for this was to create an animation based on the if-logo-then-logo style presentation of recipes used on the WTF page and elsewhere throughout the site. With 442 triggers and 172 actions available at the time of this writing, there are over 76,000 distinct recipes you can make on IFTTT. I really wanted to make something that would convey the wonderful variety of combinations that IFTTT makes possible.

The animation I was imaginging takes some visual inspiration from the spinners on a slot machine. After a little planning, I realized it wouldn’t be too difficult to pull off with some CSS sleight of hand and a bit of JavaScript. If you exclude the long list of asset urls, the finished JavaScript only weighs in around 50 lines. In this article, I’m going to explain how I was able to combine absolute positioning with overlow:hidden and a small amount of jQuery to build a neat slot machine effect that works in all major browsers.

Game plan

I decided that one easy approach would be to have three types of elements:

  • A mask: a wrapper div (or mask div) with a fixed size, position: relative and overflow: hidden. For this project, I chose the class name slottt-machine-recipe__mask.
  • An inner container to hold the icons: an inner div to hold the icon images with position: absolute. For this project I chose the class name slottt-machine-recipe__items_container.
  • The actual icons: I’m fortunate that IFTTT’s great design team had already done the work of preparing nice looking assets in standard sizes for each channel supported on our platform. To get around some weird issues I was having with unwanted extra spacing below img elements, I chose to make square divs with the icon images set as their backgrounds. I marked each icon div with the class slottt-machine-recipe__item

This setup is sufficient to conceal all but the “current” icon. The animation is achieved by manipulating the top property on the absolutely positioned container. To drive home the CSS setup, you can see what this arrangement looks like with overflow: hidden commented out and some extra border styles turned on:

CSS setup

Writing the CSS

All together, the CSS for those different elements looks something like this:

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
29
30
31
32
33
34
35
.slottt-machine-recipe__mask {
    position: relative;
    overflow: hidden;
    width: 150px;
    height: 150px;
    display: inline-block;

    // These make the icons look better while
    // sitting inline with the if/then text.
    margin-left: 10px;
    margin-right: 10px;
    margin-bottom: -20px;

    // This border style is shown in the screenshot
    // but is not used in the final effect.
    /* border: 2px solid red; */
}

.slottt-machine-recipe__items_container {
    position: absolute;

    // This border style is shown in the screenshot
    // but is not used in the final effect.
    /* border: 2px dotted green; */
}

// The actual icon images will be set as
// backgrounds on divs of this class.
.slottt-machine-recipe__item {
    width: 150px;
    height: 150px;
    margin: 0px;
    padding: 0px;
    background-size: contain;
}

Building the HTML

1
2
3
4
5
6
7
8
9
10
11
12
13
<div class="slottt-machine-recipe">
  <span class="recipe_if">if</span>
  <div class="slottt-machine-recipe__mask" id="trigger_slot">
      <div class="slottt-machine-recipe__items_container">
      </div>
  </div>

  <span class="recipe_then">then</span>
  <div class="slottt-machine-recipe__mask" id="action_slot">
      <div class="slottt-machine-recipe__items_container">
      </div>
  </div>
</div>

Starting with this basic skeleton, I still needed to add the divs for each icon. Since I had such a large number of icons to display and I wanted to be able to easily change them in the future without crawling through the raw html, I chose to build the innermost icon divs programmatically from a list of urls. I omitted the list to save space, but want to show the general approach:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
var triggers = [
  // a giant list of icon image urls
]

var actions = [
 // another giant list of icon image urls
]

function buildSlotItem (imgURL) {
    return $('<div>').addClass('slottt-machine-recipe__item')
                      .css({'background-image': 'url(' + imgURL + ')'})
}

function buildSlotContents ($container, imgURLArray) {
  $items = imgURLArray.map(buildSlotItem);
  $container.append($items);
}

This code gets invoked to build a div for each icon after the page is loaded:

1
2
3
4
5
6
7
8
9
$(document).ready( function () {
  $trigger = $('#trigger_slot .slottt-machine-recipe__items_container');
  buildSlotContents($trigger, triggers);

  $action = $('#action_slot .slottt-machine-recipe__items_container');
  buildSlotContents($action, actions);

  setInterval(animate, 3500); // I'll talk about this later.
});

Basic Animation

Since the inner div has position: absolute we can position it precisely with respect to the parent div as long as the parent has position: relative. This means that changing which icon is displayed in the non-hidden area of the mask div can be done by setting the top position property on the inner container div to a multiple of the image size (150 pixels in this case).

From there, making a “sliding” effect is just a matter of animating the change of the top property with jQuery’s animate function (docs here). We could have written our own loop to take care of this, but jQuery has already done a nice job of implementing different easing functions, like swing, that specify a property’s rate of change over time. Using non-linear easing gives the animation a nice polished feel.

1
2
3
4
5
6
7
function animate() {
  var triggerIndex = randomSlotttIndex(triggers.length);
  $trigger.animate({top: -triggerIndex*150}, 500, 'swing');

  var actionIndex = randomSlotttIndex(actions.length);
  $action.animate({top: -actionIndex*150}, 700, 'swing');
}

Forever upward

By now we are 90% to the finished result. But instead of randomly scrolling the icons up or down, I really wanted them to scroll infinitely in the same direction. To pull this off we need to do a small amount of extra work to pop elements off the top of our inner container and push them onto the end. By doing this, we can always scroll in the same direction without running out of icons to display.

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
29
30
31
32
33
34
// Take the first n child elements from the $container and move them
// to the end.
function popPushNItems ($container, n) {
    $children = $container.find('.slottt-machine-recipe__item');
    $children.slice(0, n).insertAfter($children.last());

    if (n === $children.length) {
      popPushNItems($container, 1);
    }
}

// After the slide animation is complete, we want to pop some items off
// the front of the container and push them onto the end. This is
// so the animation can slide upward infinitely without adding
// inifinte div elements inside the container.
function rotateContents ($container, n) {
    setTimeout(function () {
      popPushNItems($container, n);
      $container.css({top: 0});
    }, 300);
}

function animate() {
  var triggerIndex = randomSlotttIndex(triggers.length);
  var actionIndex = randomSlotttIndex(actions.length);

  $trigger.animate({top: -triggerIndex*150}, 500, 'swing', function () {
    rotateContents($trigger, triggerIndex);
  });

  $action.animate({top: -actionIndex*150}, 700, 'swing', function () {
    rotateContents($action, actionIndex);
  });
}

You can see the resultant effect best by turning off the mask div’s overflow:hidden property:

Fine-tuning slide distance

For the basic version of the animation, I was just choosing a random icon to scroll to with a function like this:

1
2
3
function randomSlotttIndex(max) {
  return (Math.random() * max | 0);
}

This was sufficient to test other aspects of the project, but in the finished product I really want to ensure that the icon we’re spinning to is sufficiently “far” away that the random slot machine feel is preserved; randomly choosing to stay at the current position or roll to an icon only a few notches away just isn’t as satisfying. So, we modify our random index selection to account for that and reject small index choices.

1
2
3
4
function randomSlotttIndex(max) {
  var randIndex = (Math.random() * max | 0);
  return (randIndex > 10) ? randIndex : randomSlotttIndex(max);
}

It’s not a problem to reject these small indices as slide targets because of the way we are popping elements off and pushing them onto the end. All the icons will be cycled through the different positions and will eventually be selected for display.

Conclusion

That about wraps it up, and I hope you learned something that will be useful to you in your future projects. You can view and tinker with the finished result on codepen.io.

Improve Your Animation Performance With requestAnimationFrame

At their most basic core, browser animations have the following structure:

  1. Make some calculations
  2. Update the plot
  3. Goto 1.

A not-great way of doing this is with the timer functions provided by the browser:

1
2
3
4
5
6
function animate() {
  makeCalculations();
  updatePlot();
}
var timestep = 50 // 50 ms, e.g. 20 fps;
window.setInterval(animate, timestep);

When timers aren’t on time

This will get the job done, but the results often leave much to be desired. The animation may be choppy and uneven because timers are handled in the same thread of execution as other asynchronous browser events, and may not fire precisely when you’d like.

For the smoothest animations, we’d like to use a very small timestep between frames. This is a bit of a conundrum because decreasing the size of the timestep makes deviations from perfect timing the most noticeable. This is because the same amount of absolute error in our timing function will represent a larger precentage of a smaller interval.

Monitor refresh effect

Crazy things can happen when the rate of change in a phenomenon (in the browser, or in life) is happening at a different rate than we can percieve it. In the study of optical illusions, the wagon-wheel effect is when we percieve motion to be slowed or even reversed from the true direction of motion. This occurs because of “temporal aliasing” by the recording medium into discrete frames.

For browser animations, the lesson to take from this is that the difference between our animation’s fps and the monitor’s refresh fps can have a big impact on the percieved smoothness of our animation. Nat Duca and Tom Wilzius discussed this form of “jank” in their Google I/O presentation Jank Free: Chrome Rendering Performance.

Render performance with requestAnimationFrame

Browser developers have given us a better alternative for animations called requestAnimationFrame. rAF should get called when you are ready to draw another frame, and the browser will know to update before it’s next repaint to give you the best possible render performance.

Our simple example above becomes

1
2
3
4
5
6
7
function animate() {
  makeCalculations();
  updatePlot();
  requestAnimationFrame(animate);
}

requestAnimationFrame(animate);

Browser support is getting pretty good, and there are polyfills available that will fall back to setInterval where it’s unsupported.

Now go forth and requestAnimationFrame!

Building Elementary Cellular Automata in Ruby

Cellular automata are simulations where each location in a space can have a finite number of states (usually on or off, or 0 and 1). The state at a particular location can change through time according to specific rules. Most such systems are fairly boring, but some sets of rules can give rise to surprisingly complex behavior. Whole branches of math and computer science are devoted to the study of these simulations.

There’s a good chance you’ve seen an implementation of Conway’s Game of Life, which is the most well-known example of cellular automation. Life is set on a two-dimensional grid, and self-replicating patterns called gliders are a common occurance.

I am not a computer scientist, but I find the dancing patterns mesmerizing. As a fun exercise, I decided to take my layman’s knowledge of cellular automation and build my own implementation of the 256 different Elementary Cellular Automata. These are also very beautiful, but have so far made a much smaller pop culture splash than their cousin Life.

Elementary Cellular Automata

The Elementary in Elementary Cellular Automata comes from the fact that the model space is restricted to only one dimension. The grid in this case is a single row of pixels. Rather than animating a one-pixel row, most representations of ECAs show time on the vertical axis by printing a new row for each timestep.

From one time-step to the next, a pixel will live or die according to rules that examine the state of a pixel and the state of its two neighboring pixels. For convenience, we might represent the pattern in a particular location as the a three-digit string like 101 or 001. Since a particular pixel and its two neighbors can each be either a 1 or a 0, there are 2*2*2 = 8 different possible patterns at a particular location. The Wikipedia article goes into a lot of detail about how these rules are derived.

Program organization

A principal in good object-oriented design is to separate things that change from things that don’t change. With that in mind, I decided to use the composite pattern for the main ElementaryCellularAutomata class and abstract the changeable portions of the simulation logic their own classes.

The 256 different kinds of rules into a Rule class. A factory method configures the rule class to have a different behavior depending on the rule number.

I also handle print functions in a Printer class following a template pattern. This is so I can easily print output to the console with one class, or save to png image with anohter. And I could easily extend it to other types of printers in the future (PDF, jpg, etc) as long as those classes provide a print method.

You can check out the finished code and a gallery of the output on github.

JavaScript reboot

Just for fun, I decided to build an animated JavaScript version of this code.

See the Pen Elementary Cellular Automata by Jennifer Hamon (@jhamon) on CodePen.