Arduino Nixie Tube Bar Graph Control With TLC5628CN

Check out these tubes, pretty bad ass, don’t you think? With the help of Daniel Naito’s amazing project and the TI TLC5628CN 8-bit serial DAC I’ve managed to get my Arduino controlling an IN-13 tube. I’ve got simple 3 wire serial communication working with the TLC5628 (thanks Ogi Lumen), and but I’m only utilizing one DAC right now. The nixie tubes on the left are facing up and therefore are hard to see, but they are cycling 0-9-0.

Playing with the Arduino

I might have mentioned previously that I recently bought an Arduino Duemilanove. It’s pretty damn cool and I’m amazed at the amount of power you can get for such small price (and form factor).

My first month or so was spent hooking it up to LED’s and the Ethernet Shield. I wasted a bunch of time on a poorly thought out messaging system. I had LED’s hooked up to PWM outputs and was controlling their brightness independently from my computer. It was a great learning experience and the perfect way to remind me how to write C. Luckily for us all, that code has been scrapped (it can probably be found at the first revision on Github).

This week I got a package from Canada. “What comes from Canada?” you might ask. Not much, but there is a place that loves to ship NOS Russian Nixie tubes. Ogi Lumen has been a pleasure to deal with, and provides a top quality kit. Assembling the Nixie Driver kit took about an hour, and getting it up and running was smooth as can be. Ogi Lumen provides a concise and well written library with only a handful of functions for the developer to learn.

Tomorrow I’m giving a lightning talk at work about all this. I’ve spent the better part of the evening putting together some code to help with a demo. I’ve cleaned up the messaging protocol a bit (it still needs major refactoring, but I’ve opted to keep it simple). Now I have a few different kinds of messages, as well as minor error handling. I’ve set up a simple way to clear the Nixie tubes, a command to left justify some digits (and continuously shift them to the right) as well as right justify the display (with no shifting). But my ace in the hole is a demo command I’ve put together that will do some cool cycling of content across the tubes.

Ok, so it’s still not all that exciting, eventually I’ll buy more than two tubes. First though, I have plans to conquer this beast: Neon Bar Graph. I’ve placed an order from Digi-Key for a few discrete components to get myself started, eventually building a shift register/DAC driver similar to the Ogi Lumen Nixie Tube Driver kits (probably without the cool boards though).

Get My Patch Added to Core

Help me out here. I came across what I think is a bug in Rails core. It’s a really small issue, and an even smaller patch. Seriously, it’s only two lines of code, and three new tests — as you can see in the Lighthouse Ticket.

Oh, you want a description? The description I wrote in the ticket wasn’t enough? Fine, I’ll expand a bit here. First, let me state that this issue was only uncovered due to our semi-unorthodox deployment strategy. I say semi-unorthodox because I’ve never read of anyone else using a similar style, but I don’t see an alternative.

Here at work we build apps for two sets of users: the public and our business team. These sets of users see totally different applications; in fact, they aren’t even running on the same boxes. Think of our internal tool as a CMS and Customer Service tool. Instead of writing two applications and making them share models, we have one larger application but can control how it reacts by changing the RAILS_ENV. Our basic configuration contains three environments: development, production and admin (this is a simplification: we also have multiple test environments, but they are unimportant for the sake of this discussion).

To limit what can take place on each environment we have segregated our routes.rb like you see below.

# back end services
if %w(admin development test).include?(RAILS_ENV)
    path_prefix = (RAILS_ENV == "development") ? "admin" : "")
    map.namespace(:admin, :path_prefix => path_prefix) do |admin|
      admin.connect "/applicants/:id", :controller => "applicants", :action => "show"
    end
end

# front end site
if %w(production development test).include?(RAILS_ENV)
    map.root :controller => "applicants", :action => "new"
end

Let’s go over this routing real quick. You’ll immediately notice two blocks, the first being for “back end services” (i.e.: internal business users), and the second for the “front end site” (i.e.: the public). If you look closely you’ll see the only difference between the conditionals for each block is that the first includes the “admin” environment while the second uses the “production” environment.

The issue I ran into stems from line #3. When path_prefix is blank, RouteBuilder generates improper URLs, therefore affecting everything inside the admin namespace.

  • When path_prefix is set, the admin URLs look like: /admin/applicants/1
  • When path_prefix is blank they look like: //applicants/1

That extra slash is a bit of a problem with the way we deploy our “admin” environment. We use some Apache fu to map http://admin/project to the root of the application, meaning our internal users need to go to http://admin/project//applicants/1. This URL is clearly incorrect and should never be generated.

Without the path_prefix we are severely limited in our ability to run the full project in development mode. With the path_prefix set in “development” mode we can view the public portion of the site at http://localhost:3000/applicants/1 and the private part at http://localhost:3000/admin/applicants/1. It should be noted that these two routes go to two completely different controllers, one being in the global namespace, and the other existing inside an Admin module.

Now I know if you payed attention you’re probably thinking: “Andrew, you can get around this with a simple refactor, maybe try this…”

path_prefix = (RAILS_ENV == "development") ? "admin" : nil)

Yes, you’re right, that would work: having the path_prefix set to nil is a simple solution. But, a bug is a bug, and adding an extra slash to a URL isn’t an appropriate thing to do. So please, if you made it this far and you don’t think I’m a raving loon then +1 my patch.

Rails Defaults I Like to Change

When working on larger projects the RAILS_ROOT/app folder structure can be a little restrictive. Lately I’ve taken to adding more sub-directories into RAILS_ROOT/app like, observers, mailers and presenters (check out ActivePresenter and Presenter Pattern if you’ve never heard of it). It’s a simple trivial addition to the folder structure that allows me to keep my sanity. Instead of sifting through 40+ files in the models folder I can quickly drill down to what I’m looking for.

Luckily, Rails is nice enough to have a simple mechanism to do this. Open your environment.rb file and look for the lines that read:

  # Add additional load paths for your own custom dirs
  # config.load_paths += %W( #{RAILS_ROOT}/extras )

Simply un-comment the second line and replace it with something like this:

  # Add additional load paths for your own custom dirs
  config.load_paths += %W( #{RAILS_ROOT}/app/clients #{RAILS_ROOT}/app/observers #{RAILS_ROOT}/app/presenters #{RAILS_ROOT}/app/mailers )

Very similar to moving the Ruby files around, I have also taken to moving some of the views around, specifically, mailer views. I like to keep them near the mailer model, and not in the RAILS_ROOT/app/views path.

This change is also quite easy thanks to the extensibility of the Rails framework. Near the end of your environment.rb file add the following line:

  config.action_mailer.template_root = "#{RAILS_ROOT}/app/mailers"

Tall Mocha, no toppings please

I finally got around to using a mocking library today at work. I chose Mocha to start, no real reason, just the first name to pop into my head. After about 15 minutes (10 reading docs, and 5 coding) I am in love. Seriously, testing has never been this easy. What would have taken me at least 30 minutes to add new fixtures wihtout breaking old tests or screwing anything else up was easily solved in one to 2 lines per test case.

class SupportControllerTest < ActionController::TestCase
  def test_applicant_activated_view
      Applicant.any_instance.expects(:activated?).returns(:true)

      post :create, :applicant => {:last_name => "Leapfrog", :email => "sos_platform@leapfrogqa.com"}
      assert_select "ul.activated"
  end
end

The first line in the above method mocks out the activated? method on any instance of the Applicant class. Isn’t that simple and clean? Without seeing the rest of the business logic I know it might be hard to accept why I need an entire library to help me with this simple boolean method, but trust me, activated? method is actually delegated to another model which is using an ActiveResource object to truly determine the result.

Prototype Scroller Object

Recently an old friend, David Moffitt, asked me to tweak some Javascript I wrote for him and his company GTTS over a year ago. Looking at it again after such a long time was scary. The code was terrible. All functions, no classes, just a mess. I rewrote it for them as a Prototype based Class. Very clean and easy.

The Scroller object creates a simple news ticker that nicely rotates messages, stops when you mouse over, and continues when you mouse out. Yep, thats it. Check out my github project. View the comments in scroller.js for directions on how to use it.

Why the almost empty github project? The theory is I might one day write more Javascript and need a place to put it. So for now, only one file in that “project” but just you wait.

ERB templates of ERB templates

Recursion, every programmers favorite topic. Luckily that’s not what this is about, really. Today at work I was writing a Rails Generator that needed to created <a href=”http://www.ruby-doc.org/stdlib/libdoc/erb/rdoc/”>ERB</a> templates for views. It sounded pretty simple, but I hit one stumbling point. How do I make my template an ERB template that generates an ERB template of its own without interpreting all of the tags? After a bit of Googling I started to get discouraged. Then I remembered Rails already does some of this in places like the scaffold generator. I opened up the source and the templates and found an ERB tag I had never seen before <code><%%= do_something %></code>. There it was, the ‘%%’ will tell ERB to treat this as a tag for a future run. It will remove the second % and leave you with the output you expect.

Announcing Plugistrano v0.0.1

Plugistrano is a little project I’ve been pondering for a while. My boss Jeff Cohen came up with the idea a few weeks ago. While in Portland at RailsConf 2008 I made some progress with it, thanks to the help of my coworker Mike.

Check out the github repo. Let me know what you think, fork it, fix it and make it better.

note: I have only tested this (very briefly) with Capistrano 1.4.1. It might not work with 2.0. I will try to test it with 2.0 later

More Testing Thoughts - When Mocks Can’t Help

The other day I found myself needing to test a class (this seems to happen a lot), but I ran into a sticky situation. I wanted to test the validity of an instance method, easy enough, and then later wanted to test another instance method that relies on the first. The problem lies in the fact that the first relies on an external service that doesn’t provide stable data, making it difficult, if not impossible to test.

A little background on the code you’re about to see. It is quite common that I must consume XML from internal services, but I have no way of knowing how much data will be returned with each request (as these feeds rely on other services). Downloading tons of XML and iterating over it (and performing actions based on the data) is slow, cumbersome and can cause annoying situations if it crashes in the middle. To help with scalability (the buzzword of the year!) the XML feed listens for 2 query string parameters, start_event and limit. Knowing this I built a small iterator object to wrap a Hpricot instance and fetch XML with only 100 rows, and to repeat until it has reached the end.

Boring business logic and methods have been removed from the following sample.

class XmlIterator
  include Enumerable

  ...

  def each
    while data = get_xml(build_url)
      results = (data/@search_term)
      results.each{|x| yield x}

      @start_event = (data/'activations').first['end_event']

      break if results.length < @limit
    end
  end

private
  def build_url
    query_string = "start_event=#{@start_event}&limit=#{@limit}"

    return "#{@path}?#{query_string}"
  end

  ...
end

As you can see, I’ve built my own enumerable object, but the each method is really a proxy back to a Hpricot doc object (produced in the get_xml method I have conveniently removed). It will fetch 100 rows, process them, and then fetch 100 more, and continue until the result set is returning less than 100, meaning it was the last “page” of data.

Now for the testing. Validating build_url was pretty simple, set some instance variables, call the method and compare the returned string. But what about each? I don’t want to hit the service to test the each method, it would really be great if I could have it look at a local file in my mocks directory. All I really care to test here is that the proxying of the iteration works as expected. I struggled with how to do this for a few hours.

My initial reaction was to mock up the HTTP service using something like WebBrick, but that sounded like a lot of work, and a maintenance nightmare in the future. I knew the solution was to change the build_url method, but how can I do that without overriding it completely, as I need to test the original implementation. This meant placing a file in test/mocks/test was out.

Then it hit me, why not just change the build_url for that one test. There are 2 ways to go about this (that I know of). Both can be seen in the example below:

require File.dirname(__FILE__) + '/../test_helper'

class XmlIteratorTest < ActiveSupport::TestCase
  def setup
    @iterator = XmlIterator.new("http://www.madeup.com")
  end

  def test_each
    def @iterator.build_url
      "#{RAILS_ROOT}/test/mocks/test/activations.xml"
    end

    ...
  end

  def test_each_again
    @iterator.instance_eval do
      def build_url
        "#{RAILS_ROOT}/test/mocks/test/activations.xml"
      end
    end

    ...
  end
end

Both @iterator.instance_eval and def @iterator.build_url will produce the same result, a new version of build_url for that specific instance of @iterator, it’s just a matter of preference which you chose to do. Personally, since it’s just one method I’m redefining I like the first version, but if I was overriding 2 or more I’d probably go with the second.

Logging in Rails

When you’re living in the Active* world of Rails (ActiveRecord, ActionController, etc.) you always have access to the ubiquitous logger method. But step outside and you’re stuck dealing with the awkward, and uncomfortable RAILS_DEFAULT_LOGGER global. Often time’s I find myself taking one or both of the following approaches depending on the class I’m writing.

class MadeUp
  class << self
    def logger
      RAILS_DEFAULT_LOGGER
    end
  end

  def logger
    RAILS_DEFAULT_LOGGER
  end
end

Now I know, neither of the methods are complex or long, but how often do you want to type that same handful of lines (and doesn’t it just make your code ugly)? Enter my latest and greatest contribution to the world: Loggable.

module Loggable
  module ClassMethods
    def logger
      RAILS_DEFAULT_LOGGER
    end
  end

  module InstanceMethods
    def logger
      RAILS_DEFAULT_LOGGER
    end
  end

  def self.included(receiver)
    receiver.extend         ClassMethods
    receiver.send :include, InstanceMethods
  end
end

Object.send :include, Loggable

Remember to require it somewhere in your code.

Rambling one post at a time