Archive

Posts Tagged ‘rails’

Really really simple Ruby metaprogramming

February 5th, 2011 12 comments

Metaprogramming in Ruby has the reputation of being something only the true zen Ruby masters can even hope to understand. They say the only true way to learn metaprogramming is to train with Dave Thomas in his mountain retreat for five years – the Ruby equivalent of this XKCD:

But it’s not that bad. In fact, I’m going to go so far to say that it’s possible to learn to metaprogram in Ruby without even meeting Dave Thomas. Yeah, I know, it doesn’t sound possible. But just you wait…

What is metaprogramming?

Metaprogramming is what makes Ruby awesome. It’s writing code to write code. It’s dynamic code generation. It’s the move from imperative to declarative. It’s a rejection of Java’s endless repetition of boilerplate code. It’s the living embodiment of DRY. Here’s an example:

class Monkey
  def name
    @name
  end

  def name= n
    @name = n
  end
end

I can see you there, in the middle of the classroom, with one arm straining up, the other one holding it up because it’s so damn hard to hold up. OK, Jimmy, what is it? Oh, you don’t need to write all that code in Ruby? You can just use attr_accessor?

Jimmy’s right. That code snippet above could be written like so:

class Monkey
  attr_accessor :name
end

So, attr_accessor‘s magic right? Well, actually, it’s not. Just like in Scooby-Doo where what looked like magic to start off with turned out to be an elaborate hoax, attr_accessor is just a class method of Module. It defines the name and name= methods on Monkey, as if you’d manually defined them.

And that’s all metaprogramming is. Just a way of adding arbitrary code to your application without having to write (or copy-paste) that code.

An (extended) example

The source code for this example is available in my StringifyStuff plugin on github, which in turn was adapted from Ryan Bates’ Railscast Making a Plugin. Incidentally, if you feel you can improve the plugin, fork me on github!

I’m assuming basic knowledge of Ruby, and some familiarity with Rails would be helpful as well, but not essential.

Have a quick peek at the github repo now – the important files to look at for now are init.rb and lib/stringify_time.

First, stringify_time. This file defines a module called StringifyTime, which defines a method called stringify_time:

module StringifyTime
  def stringify_time *names
    #crazy stuff going on in here
  end
end

The other two files, stringify_stuff and stringify_money are similar.

Now, init.rb:

class ActiveRecord::Base
  extend StringifyStuff
  extend StringifyTime
  extend StringifyMoney
end

This extends ActiveRecord::Base with the three modules listed. This now means that any class that inherits from ActiveRecord::Base (e.g. your models) now has the methods defined in each of those modules as class methods.

The StringifyStuff plugin is used like so:

class Project < ActiveRecord::Base
  stringify_stuff
  stringify_time :start_date, :end_date
end

stringify_time is passed a list of symbols representing the relevant model attributes. It will provide useful accessors for those attributes. Let’s have a look at a simplified version of stringify_time:

module StringifyTime
  def stringify_time *names
    names.each do |name|

      define_method "#{name}_string" do
        read_attribute(name) &&
          read_attribute(name).strftime("%e %b %Y").strip()
      end

    end
  end
end

stringify_time is passed a list of symbols. It iterates over these symbols, and for each one calls define_method. define_method is the first clever Ruby metaprogramming trick we’re going to look at. It takes a method name and a block representing the method arguments and body, and magically adds an instance method with that name, arguments and body to the class in which it was called. In this case, it was called from Project, so this will gain a new method with the name "#{name}_string". In this example, we passed in :start_date and :end_date, so two methods will be added to Project: start_date_string and end_date_string.

So far so good. Now though, it gets a little bit hairy, so hold onto your horses (or equivalent equid).

In a normal model instance method, you’d access an attribute using a method of the same name. So if you wanted to get the start_date converted to a string, you’d write:

def my_method
  start_date.to_s
end

The problem with doing this in define_method is that we don’t have start_date as an identifier – it’s held as a symbol. There are two ways to accomplish the above if start_date was passed in as a symbol:

def my_method attr_sym
  read_attribute(attr_sym).to_s #This is a Rails method
end

or:

def my_method attr_sym
  send(attr_sym).to_s #Ruby built-in method
end

For simplicity, I’m using write_attribute, but send is useful to know about too.

So, back to define_method:

      define_method "#{name}_string" do
        read_attribute(name) &&
          read_attribute(name).strftime("%e %b %Y").strip()
      end

So, each time round the loop, name will be one of the symbols passed into stringify_time. Let’s go with start_date to see what happens. define_method will define a new instance method on the Project class called start_date_string. This method will check to see if there is a non-nil attribute called start_date, and if so, call strftime on it. This formatted date will be the return value of the method.

Wrap up

That’s more than enough for one day (I’ve been told off for writing kilo-word posts before). I’ll explain the workings of the rest of the plugin in a future post. If you want to learn more, I highly recommend David Flanagan’s The Ruby Programming Language.

Metaprogramming is writing code that gives you more code. It’s a bit like the Sorcerer’s Apprentice; in fact, I think that should be recommended watching for this subject.

Be the Sorcerer. Don’t be Mickey.

Categories: Programming Tags: , ,

Nike: all your runs are belong to us

August 3rd, 2010 1 comment

I like to run, and I like tech, so obviously I like to measure and graph my runs. So I use Nike+. Unfortunately, Nike+ has a rubbish pure-flash website (rant: do people still make pure-flash sites? This is 2010!).

I want a way to get to my run data without having to use Nike’s website, so I’ve decided to code something up. I’m learning Rails at the moment, so I’ve decided to do this as a Rails app. In this post, and probably some subsequent posts, I’ll be showing my progress.

Step 1: getting the data

First off, we need some way of getting the data from Nike. This post on labs.interfacedigital.co.uk shows how to get the raw run data through Nike’s public API. The two URLs we’ll be using are this one for getting a summary of all runs:

http://nikerunning.nike.com/nikeplus/v1/services/app/run_list.jsp?userID=#{user_id}

and this one for getting the details of a single run:

http://nikerunning.nike.com/nikeplus/v1/services/app/get_run.jsp?id=#{run_id}&userID=#{user_id}

The all runs XML looks like this:

<plusService>
  <status>success</status>
  <runList endIndex="-1" startIndex="0">
    <run id="1752070113" workoutType="standard">
      <startTime>2010-02-28T13:24:40+00:00</startTime>
      <distance>6.264</distance>
      <duration>4067000</duration>
      <syncTime>2010-02-28T14:34:16+00:00</syncTime>
      <calories>470.0</calories>
      <name/>
      <description/>
      <howFelt>3</howFelt>
      <weather>2</weather>
      <terrain>1</terrain>
      <intensity/>
      <gpxId/>
      <equipmentType>sportband</equipmentType>
    </run>
    ...
  </runList>
</plusService>

Step 2: read the data

I’m doing the following in a Rails model called Run. The underlying table has fields for the necessary run attributes. I’m not going to go into this in detail because this isn’t a Rails tutorial.

require 'open-uri'
require 'rexml/document'

...

attributes = {
 #:attr         #xml tagname
  :distance   => "distance",
  :start_time => "startTime",
  :duration   => "duration",
  :calories   => "calories"
}

open(all_runs_url) do |f|  #open the XML file using the open-uri library
  doc = REXML::Document.new f.read  #create a new REXML object
  doc.elements.each("plusService/runList/run") do |run_info|  #iterate over 'run' elements
    run_id = run_info.attributes["id"]  #get the Nike id of the run
    run = find_or_initialize_by_run_id(run_id)  #get a new Run object, either from an existing record
                                                #in the database or create a new one

    attributes.each do |key, value|  #iterate through attributes hash, which maps object attrs to XML tags
      run.write_attribute(key, run_info.elements[value].text)
    end

    run.calculate_avg_pace  #work out the average pace
    run.save
  end
end

calculate_avg_pace looks like this:

def calculate_avg_pace
  self.avg_pace = duration_in_minutes / distance_in_miles
end

and uses the following virtual attributes:

def duration_in_minutes
  duration / (60.0 * 1000)
end

def distance_in_miles
  distance * 0.62
end

At some point I’ll refactor so miles/km is an option, but for now I just want to get something working. So far though, so good:

First run listing

First run listing

Next steps will be to make the numbers look a bit nicer, for example by showing average pace in mm:ss. Other than that, who knows?

Links

Categories: Programming Tags: , ,