The Year 2013 — A Summary

Every December, I write a recap of the year that’s gone. I’m a couple of days late this time, but I’d still like to write about some of our highlights from 2013.

Need For Speed™ Network

2013 was dominated by our biggest and most ambitious project yet: Need For Speed™ Network for our new clients Ghost Games and EA. We had pretty much the full team working on this project for most of the year. We’re not completely done with it yet, and we’ll have more to say when we’re finished. In the mean time, check out the promo video for the app.


Our own product ProjectPuzzle has been left mostly unattended since we launched it in 2012. We had several new customers sign up during 2013 though, and we received lots of great feedback from people who tried it out. We’ve started working on the next version of ProjectPuzzle, and I’m really looking forward to sharing the progress of that with you in the coming months.

Nordic Ruby

The 4th annual Nordic Ruby was the best one yet. It was probably also the last one, in a way. We’re changing things a bit for 2014.

I wrote a blog post about Nordic Ruby 2013 with lots of great photos and video. Check it out if you haven’t already.

Part of the team at Nordic Ruby 2013

Anders T

At the end of November we said goodbye to Anders Törnqvist. Anders was one of the original 4 team members at Elabs, and after 5 great years here he wanted to try switching from consulting to working in a product company. We wish him the best of luck with his new job at PugglePay.

Anders Törnqvist

What’s next?

Right now we’re working hard on finishing the last pieces of the Need For Speed™ Network project, and after that we’re looking for new client projects. If you have something you think we can help with, please get in touch.

Other than client work, we’re also very excited about getting to work on the next versions of ProjectPuzzle and Nordic Ruby.

Here’s to 2014.

/ CJ


Nordic Ruby 2013

Earlier this month, we held the fourth edition of Nordic Ruby, the conference we organise every year. Just like last year we held it at Hasseludden Yasuragi, a beautiful Japanese-style spa in the Stockholm archipelago.


I couldn't be happier with the way the conference turned out this year. We had some incredible talks from our fantastic speakers, and I had a wonderful time meeting old friends and making new ones.

CJ on stage

If you want to see more of what Nordic Ruby was like this year, you'll find slides, notes, blog posts and photos in the coverage section of our Lanyrd page.

Some standout links that you'll definitely want to check out:

Speaking of what Nordic Ruby is all about, I think this year's conference showed that it's not about Ruby in any case. It's never been really, but we haven't done a good job communicating that. That's changing.


Nordic Ruby will be back next year, but it won't be called Nordic Ruby any more. The name of the conference will be different, but the feeling of it will stay the same. If you want to keep up with our announcements about it, make sure you follow @nordicruby on Twitter.

See you next year!

Nordic Ruby 2013 from Alexander Lang on Vimeo.


My Craftsman Swap with Bendyworks

Last week I flew from Sweden to Madison, WI to work for a week together with the developers at Bendyworks, or as they call themselves, Bendyworkers.

After the 23 hour flight I was met by Stephen who didn’t hesitate for a moment to welcome me to Madison in the middle of the night on a Sunday. Over the week I’ve learned that a great talent for hospitality is something that all the Bendyworkers have in common. Even though it was late Stephen gave me a quick tour around the beautiful Capitol building located right next to Bendywork’s office.

Capitol building

Bendyworkers perform their craft in a rustic triangle-shaped building built before the 1900’s. The office is located right downtown and is surrounded by a bursting number of cafés, restaurants, and even a theatre. Inside I found that the rooms are all very open and people are moving naturally between desks and programming pairs. During Bendywork’s monthly “release valve” meeting I learned that not even the owners Stephen, Brad, and Jim take a dedicated office for granted. To me this illustrates well how flat and transparent the company structure is at Bendyworks.

I had the opportunity to work on two different projects over the week. On Monday I worked together with Chris on a CMS for Internet Week New York. The project was wrapping up, since all the major features already were delivered we got some time to spend on refactoring a few acceptance tests and have them execute faster. Tuesday through Thursday I paired up with Josh on work for SEOmoz. Josh has some serious shell and terminal vim skills going on, while I’m more of a mvim user depending a bit more on Mac OS X to do window handling for me. The SEOmoz work spanned across three different Rails-based applications with a very heavy emphasis on client side JavaScript.


Bendyworkers all have a genuine passion for their craft. When they don’t attend meetups they’re working on numerous open source projects or catching up with their self-assigned book club related homework. Lunches are spent preparing for the book club or sharing knowledge through more organized presentations, like when Joe had a great walkthrough of his blogpost on giving yourself a security makeover.

With all that time spent on perfecting their craft you’d think Bendyworkers wouldn’t know how to have fun. Well, you’re wrong. Ping-pong games, comedy clubs, taco-tuesdays, arcade halls, great food and drinks just to name a few of the activities Bendyworkers have treated me to over the week.

With that, I’d like to thank Bendyworks for a week full of fun, productive, and educational experiences!


Steve Jobs on what's important in the development of a product

You know, one of the things that really hurt Apple was after I left John Sculley got a very serious disease. It’s the disease of thinking that a really great idea is 90% of the work. And if you just tell all these other people “here’s this great idea,” then of course they can go off and make it happen.

And the problem with that is that there’s just a tremendous amount of craftsmanship in between a great idea and a great product. And as you evolve that great idea, it changes and grows. It never comes out like it starts because you learn a lot more as you get into the subtleties of it. And you also find there are tremendous tradeoffs that you have to make. There are just certain things you can’t make electrons do. There are certain things you can’t make plastic do. Or glass do. Or factories do. Or robots do.

Designing a product is keeping five thousand things in your brain and fitting them all together in new and different ways to get what you want. And every day you discover something new that is a new problem or a new opportunity to fit these things together a little differently.

And it’s that process that is the magic.

— Steve Jobs, Triumph of the Nerds

Via 37signals and CNN Fortune Tech


Advanced topics in Ruby FFI

Short primer: what is FFI?

This article is not a tutorial on the basics of FFI. However, if you’ve never heard of FFI before, I’d like to wet your appetite before continuing on.

FFI is an alternative to writing C to use functionality locked within native libraries from Ruby. It allows you to explain, with an intuitive Ruby DSL, which functions your native library contain, and how they should be used. Once the functionality of your native library is mapped out, you can call the functions directly from Ruby.

Furthermore, gems using ffi do not need to be compiled, and will run without modifications on CRuby, JRuby and Rubinius! In practice there could be small differences between the platforms in the behaviour and usage of FFI, and if you find any you should report them to the Ruby FFI issue tracker so it can be dealt with.

As far as basic tutorials on using FFI, your best resource is the FFI wiki. It also has a list of projects using FFI, which is your second best resource on learning how to use FFI.

Aliasing with typedef

If we look at the header for a function from libspotify:

SP_LIBEXPORT(sp_error) sp_session_player_prefetch(sp_session *session, sp_track *track);

Naively mapping this to FFI we’ll need:

enum :error, [ … ]
attach_function :sp_session_player_prefetch, [ :pointer, :pointer ], :error

Unfortunately, we lost two pieces of valuable information here. Both sp_session and sp_track are types that occur many times in the library. When we look at the ruby implementation, there is no hint whatsoever of what type the two pointers should be of.

It does not need to be like this. Using typedef we can name our parameters, and bring back the information that we lost in our translation.

typedef :pointer, :session
typedef :pointer, :track
enum :error, [ … ]
attach_function :sp_session_player_prefetch, [ :session, :track ], :error

Functionality of our method does not change, but implementation is now slightly more clear and maintainable.

Specializing in attach_function

C libraries do not follow Ruby naming conventions, which makes sense since they’re not written in Ruby. However, bindings written with Ruby FFI are in Ruby and will be called from Ruby, so they should have the look and feel of Ruby.

Attach function allow you to call it in two ways:

attach_function :c_name, [ :params ], :returns, { :options => values } # 1
attach_function :ruby_name, :c_name, [ :params ], :returns, { :options => values } # 2

Using the first form will create your Ruby methods with the same name as your native library’s functions. Using the second form allows you to rename the bound method, giving it a more expected final name.

Native libraries you bind with FFI will have naming conventions of their own. For example, OpenAL will prefix it’s functions with al or alc, and camel case. libspotify will prefix it’s functions with sp_. Apart from removing the suffix, and snake_casing the function name, we want the Ruby method to be named similarly. We could repeat ourselves for every method:

attach_function :open_device, :alcOpenDevice, [ :string ], :device
attach_function :close_device, :alcCloseDevice, [ :device ], :bool

But remember! When you use FFI, you extend the FFI::Library inside a module of your own. This also means you can override the attach_function call, without your specialized version leaking to the outside world. By overriding attach_function we can avoid unnecessary noise in our FFI bindings.

def self.attach_function(c_name, args, returns)
    ruby_name = c_name.to_s.sub(/\Aalc?/, "").gsub(/(?\<\!\A)\p{Lu}/u, '_\0').downcase
    super(ruby_name, c_name, args, returns)

attach_function :alcOpenDevice, [ :string ], :device # gets bound to open_device
attach_function :alcCloseDevice, [ :device ], :bool # gets bound to close_device

This does not end here. After calling super inside attach_function you have the option of further specializing the newly bound method. You could implement automatic error checking for every API call, or alter the parameters based on native library conventions, and more. Just remember that the added complexity should be worth the savings.

FFI::Structs as parameters

Structs in FFI can be used as parameters, and is by default equivalent to specifying a type of :pointer.

class SomeStruct < FFI::Struct

attach_function :some_function, [ SomeStruct ], :void
# equivalent to:
attach_function :some_function, [ :pointer ], :void

callback :some_callback, [ SomeStruct ], :void
# equivalent to:
callback :some_callback, [ :pointer ], :void

I’d like to bring forth an alternative for your referenced struct parameters, namely FFI::Struct.by_ref. It behaves very similarly to the above, with the important difference in that it type-safety built-in!

attach_function :some_function, [ SomeStruct ], :void
some_function # this is possibly unsafe, but allowed

attach_function :some_function, [ SomeStruct.by_ref ], :void
some_function # BOOM, wrong argument type FFI::Pointer (expected SomeStruct) (TypeError)
some_function # BOOM, wrong argument type SomeOtherStruct (expected SomeStruct) (TypeError)

Further more, if you use FFI::Struct.by_ref for your callback parameters or function return values, FFI will automatically cast the pointer to an instance of your struct for you!

callback :some_callback, [ SomeStruct.by_ref ], :void
attach_function :some_function, [ :some_callback ], :void

returned_struct = some_function(proc do |struct|
  # struct is an instance of SomeStruct, instead of an FFI::Pointer

attach_function :some_other_function, [ ], SomeStruct.by_ref
some_other_function.is_a?(SomeStruct) # true, instead of being an FFI::Pointer

Keep in mind, that on JRuby 1.7.3, FFI::Struct.by_ref type accepts any descendant of FFI::Struct, and not only instances of YourStruct. See for updates.

Piggy-back on Ruby’s garbage collection with regular FFI::Structs

If we take a look again at the above code with SomeStruct as return value.

attach_function :some_other_function, [ ], SomeStruct.by_ref

In some libraries, the memory for the pointer to SomeStruct returned from some_other_function is expected to be managed by us. This means we’ll most likely need to call some function free_some_struct to specifically free the memory used by SomeStruct when the object is no longer needed. Here’s how it would be used:

  some_struct = some_other_function
  # do something with some_struct

Unfortunately, if we pass some_struct somewhere else beyond our control, we must be able to trust that the new guardian of some_struct calls free_some_struct in the future, or we will have a memory leak! Oh no!

Fear not, for FFI::Struct has a trick up it’s sleeve for us. Have a look at this.

class SomeStruct < FFI::Struct
  def self.release(pointer)
    MyFFIBinding.free_some_struct(pointer) unless pointer.null?

attach_function :some_other_function, [], SomeStruct.auto_ptr

With the above binding code, some_other_function still returns an instance of SomeStruct. However, when our object is garbage collected FFI will call upon SomeStruct.release to free the native memory used by our struct. We can safely pass our instance of SomeStruct around everywhere and to everyone, and safely remember that when the object goes out of scope and Ruby garbage collects it, FFI will call upon us to free the underlying memory!

Related to this, you should look into FFI::ManagedStruct and FFI::AutoPointer if you have not already.

Writing our own data types

class Device < FFI::Pointer
attach_function :some_function, [ ], Device

Subclassing FFI::Pointers is a convenient way of working with pointers from native libraries less generic. Using the above code, when we call some_function we’ll receive an instance of Device, instead of the FFI::Pointer we would get if we specified the return value as a :pointer.

If objects in our native library are not pointers we can’t do what we’ve done above. For example, in OpenAL there’s a concept of audio sources, but they are represented by an integer, and not a pointer. Passing arbitrary integers around is not a nice practice, so what you could do is wrap the source in an object for further use.

class Source
  def initialize(id)
    @id = id
  attr_reader :id

typedef :int, :source
attach_function :create_source, [], :source
attach_function :destroy_source, [ :source ], :void

# Usage
source =

While the code above is not bad, we could do much better by utilizing something in FFI called DataConverters. DataConverters are a way of writing code that tells FFI how to convert a native value to a ruby value and back. By doing this, we could have FFI automatically wrap source above in an object, making it completely transparent to the developer using the library.

class Source
  extend FFI::DataConverter
  native_type FFI::Type::INT

  class << self
    # `value` is a ruby object that we want to convert to a native object
    # this method should return a type of the native_type we specified above
    def to_native(value, context)
      if value # in our case, we convert a Source to an int
        -1 # if value is nil, we represent a `no source` value as -1

    # `value` is a type of the native_type specified above, we should return
    # a ruby object we wish to pass around in our application
    def from_native(value, context)

    # this is needed when FFI needs to figure out the native size of your native type
    # for example, if you want to generate a pointer to hold something of this type
    # e.g. # <= requires size to be defined and correct
    def size

    # this method is a hint to FFI that the object returned from to_native needs to
    # be kept alive for the native value in the object to remain valid, so that if we
    # return an object that automatically frees itself on garbage collection, ffi will
    # prevent it from being garbage collected while it’s still needed, mainly useful
    # for to_native methods that allocate memory
    def reference_required?

  def initialize(id)
    @id = id

  attr_reader :id

attach_function :create_source, [], Source
attach_function :destroy_source, [ Source ], :void

source = create_source # an instance of Source, created through Source.from_native! # => the native value
destroy_source(source) # converts source to native value through Source.to_native!

You could do this to all types, even pointers. Even more, you are not constrained to only doing type conversion in to_native and from_native — you could perform validation, making sure your values have the correct type, length, or what ever you may need!

If you’d like some more example of custom types, I’ve written down a few in this gist:

Implementing type safety

Do you remember what I mentioned earlier about FFI::Struct.by_ref automatically giving us some kind of type safety, preventing us from shenanigans where somebody sends invalid values to native functions? We can implement the very same kind of type safety ourselves for all types, by overriding to_native in our DataConverters.

# A to_native DataConverter method that raises an error if the value is not of the same type.
module TypeSafety
  def to_native(value, ctx)
    if value.kind_of?(self)
      raise TypeError, "expected a kind of #{name}, was #{value.class}"

We could now mix the above module into our own custom data types from the previous chapters.

# Even if we have another object that happens to look like a Source from our previous chapter,
# by having a #value method, we now won’t allow sending it down to C unless it’s an instance of
# Source or any of it’s subclasses.

# Remember Device from earlier? It’s a descendant of FFI::Pointer. Now all parameters of type Device
# will only accept instances of Device or any of it’s subclasses. All else results in a type error.

Duck-typing is very useful in Ruby, where raising an exception is the worst thing that can happen when we try to call a method on an object that does not respond to such a method. However, when interfacing with C libraries, passing in the wrong type will segfault your application with little information on what went wrong. Using this TypeSafety module, we can catch errors early, with a useful error message as a result.

Final words

Personally I really like using FFI. It’s a low-pain way of writing gems that use native libraries, and if you set your types up properly, not having a compiler that type-checks your code won’t be so bad. If you can work with native libraries through the means of FFI instead of writing a C extension, by all means do. Even if you intend on writing a C extension, using FFI can be a quick way of exploring a native API without wiring up C functions and data structures together with the Ruby C API.

Something that FFI excells at, in comparison to writing a C extension, is handling asynchronous callbacks from non-ruby threads in C. FFI can save you a lot of headache in that area.

Thank you.