Let’s Build a Simple Video Game with JRuby: A Tutorial

Ruby isn’t known for its game development chops despite having a handful of interesting libraries suited to it. Java, on the other hand, has a thriving and popular game development scene flooded with powerful libraries, tutorials and forums. Can we drag some of Java’s thunder kicking and screaming over to the world of Ruby? Yep! – thanks to JRuby. Let’s run through the steps to build a simple ‘bat and ball’ game now.

The Technologies We’ll Be Using

JRuby

If you’re part of the “meh, JRuby” brigade, suspend your disbelief for a minute. JRuby is easy to install, easy to use, and isn’t going to trample all over your system or suck up all your memory. It will be OK!

One of JRuby’s killer features is its ability to use Java libraries and generally dwell as a first class citizen on the JVM. JRuby lets us use performant Java powered game development libraries in a Rubyesque way, lean on Java-based tutorials, and basically have our cake and eat it too.

To install JRuby, I recommend RVM (Ruby Version Manager). I think the JRuby core team prefer you to use their own installer but rvm install jruby has always proven quick and effective for me. Once you get it installed, rvm use jruby and you’re done.

Slick and LWJGL

The Slick library is a thin layer of structural classes over the top of LWJGL (Lightweight Java Game Library), a mature and popular library that abstracts away most of the boring system level work.

Out of the box LWJGL gives us OpenGL for graphics, OpenAL for audio, controller inputs, and even OpenCL if we wanted to do heavy parallelism or throw work out to the GPU. Slick gives us constructs like game states, geometry, particle effects, and SVG integration, while allowing us to drop down to using LWJGL for anything we like.

Getting Started: Installing Slick and LWJGL

Rather than waste precious time on theory, let’s get down to the nitty gritty of getting a basic window and some graphics on screen:

  • First, create a folder in which to store your game and its associated files. From here I’ll assume it’s /mygame
  • Go to the Slick homepage and choose “Download Full Distribution” (direct link to .zip here).
  • Unzip the download and copy the lib folder into your /mygame as /mygame/lib – this folder includes both LWGWL and Slick.
  • In /mygame/lib, we need to unpack the natives-[your os].jar file and move its contents directly into /mygame.

    Mac OS X: Right click on the natives-mac.jar file and select to unarchive it (if you have a problem, grab the awesome free The Unarchiver from the App Store) then drag the files in /mygame/lib/native-mac/* directly into /mygame.

    Linux and Windows: Running jar -xf natives-linux.jar or jar -xf natives-win32.jar and copying the extracted files back to /mygame should do the trick.

  • Now your project folder should look a little like this:

    If so, we’re ready to code.

A Bare Bones Example

Leaping in with a bare bones example, create /mygame/verybasic.rb and include this code:

$:.push File.expand_path('../lib', __FILE__)

require 'java'
require 'lwjgl.jar'
require 'slick.jar'

java_import org.newdawn.slick.BasicGame
java_import org.newdawn.slick.GameContainer
java_import org.newdawn.slick.Graphics
java_import org.newdawn.slick.Input
java_import org.newdawn.slick.SlickException
java_import org.newdawn.slick.AppGameContainer

class Demo < BasicGame
  def render(container, graphics)
    graphics.draw_string('JRuby Demo (ESC to exit)', 8, container.height - 30)
  end

  # Due to how Java decides which method to call based on its
  # method prototype, it's good practice to fill out all necessary
  # methods even with empty definitions.
  def init(container)
  end

  def update(container, delta)
    # Grab input and exit if escape is pressed
    input = container.get_input
    container.exit if input.is_key_down(Input::KEY_ESCAPE)
  end
end

app = AppGameContainer.new(Demo.new('SlickDemo'))
app.set_display_mode(640, 480, false)
app.start

Ensure that ruby actually runs JRuby (using ruby -v) and then run it from the command line with ruby verybasic.rb. Assuming all goes well, you’ll see this:

If you don’t see something like the above, feel free to comment here, but your problems most likely orient around not having the right ‘native’ libraries in the current directory or from not running the game in its own directory in the first place (if you get probable missing dependency: no lwjgl in java.library.path – bingo).

Explanation of the demo code

  • $:.push File.expand_path('../lib', __FILE__) pushes the ‘lib’ folder onto the load path. (I’ve used push because my preferred << approach breaks WordPress ;-))
  • require 'java' enables a lot of JRuby’s Java integration functionality.
  • Note that we can use require to load the .jar files from the lib directory.
  • The java_import lines bring the named classes into play. It’s a little like include, but not quite.
  • We lean on Slick’s BasicGame class by subclassing it and adding our own functionality.
  • render is called frequently by the underlying game engine. All activities relevant to rendering the game window go here.
  • init is called when a game is started.
  • update is called frequently by the underlying game engine. Activities related to updating game data or processing input can go here.
  • The code at the end of the file creates a new AppGameContainer which in turn is given an instance of our game. We set the resolution to 640×480, ensure it’s not in full screen mode, and start the game.

Fleshing Out a Bat and Ball Game

The demo above is something but there are no graphics or a game mechanic, so it’s far from being a ‘video game.’ Let’s flesh it out to include some images and a simple pong-style bat and ball mechanic.

Note: I’m going to ignore most structural and object oriented concerns to flesh out this basic prototype. The aim is to get a game running and to understand how to use some of Slick and LWJGL’s features. We can do it again properly later 🙂

All of the assets and code files demonstrated here are also available in an archive if you get stuck. Doing it all by hand to start with will definitely help though.

A New Code File

Start a new game file called pong.rb and start off with this new bootstrap code (very much like the demo above but with some key tweaks):

$:.push File.expand_path('../lib', __FILE__)

require 'java'
require 'lwjgl.jar'
require 'slick.jar'

java_import org.newdawn.slick.BasicGame
java_import org.newdawn.slick.GameContainer
java_import org.newdawn.slick.Graphics
java_import org.newdawn.slick.Image
java_import org.newdawn.slick.Input
java_import org.newdawn.slick.SlickException
java_import org.newdawn.slick.AppGameContainer

class PongGame < BasicGame
  def render(container, graphics)
    graphics.draw_string('RubyPong (ESC to exit)', 8, container.height - 30)
  end

  def init(container)
  end

  def update(container, delta)
    input = container.get_input
    container.exit if input.is_key_down(Input::KEY_ESCAPE)
  end
end

app = AppGameContainer.new(PongGame.new('RubyPong'))
app.set_display_mode(640, 480, false)
app.start

Make sure it runs, then move on to fleshing it out.

A Background Image

It’d be nice for our game to have an elegant background. I’ve created one called bg.png which you can drag or copy and paste from here (so it becomes /mygame/bg.png):

Now we want to load the background image when the game starts and render it constantly.

To load the game at game start, update the init and render methods like so:

def render(container, graphics)
  @bg.draw(0, 0)
  graphics.draw_string('RubyPong (ESC to exit)', 8, container.height - 30)
end

def init(container)
  @bg = Image.new('bg.png')
end

The @bg instance variable picks up an image and then we issue its draw method to draw it on to the window every time the game engine demands that the game render itself. Run pong.rb and check it out.

Adding A Ball and Paddle

Adding a ball and paddle is similar to doing the background. So let’s give it a go:

def render(container, graphics)
  @bg.draw(0, 0)
  @ball.draw(@ball_x, @ball_y)
  @paddle.draw(@paddle_x, 400)
  graphics.draw_string('RubyPong (ESC to exit)', 8, container.height - 30)
end

def init(container)
  @bg = Image.new('bg.png')
  @ball = Image.new('ball.png')
  @paddle = Image.new('paddle.png')
  @paddle_x = 200
  @ball_x = 200
  @ball_y = 200
  @ball_angle = 45
end

The graphics for ball.png and paddle.png are here. Place them directly in /mygame.

We now have this:

Note: As I said previously, we’re ignoring good OO practices and structural concerns here but in the long run having separate classes for paddles and balls would be useful since we could encapsulate the position information and sprites all together. For now, we’ll ‘rough it’ for speed.

Making the Paddle Move

Making the paddle move is pretty easy. We already have an input handler in update dealing with the Escape key. Let’s extend it to allowing use of the arrow keys to update @paddle_x too:

def update(container, delta)
  input = container.get_input
  container.exit if input.is_key_down(Input::KEY_ESCAPE)

  if input.is_key_down(Input::KEY_LEFT) and @paddle_x > 0
    @paddle_x -= 0.3 * delta
  end

  if input.is_key_down(Input::KEY_RIGHT) and @paddle_x < container.width - @paddle.width
    @paddle_x += 0.3 * delta
  end
end

It’s crude but it works! (P.S. I’d normally use && instead of and but WordPress is being a bastard – I swear I’m switching one day.)

If the left arrow key is detected and the paddle isn’t off the left hand side of the screen, @paddle_x is reduced by 0.3 * delta and vice versa for the right arrow.

The reason for using delta is because we don’t know how often update is being called. delta contains the number of milliseconds since update was last called so we can use it to ‘weight’ the changes we make. In this case I want to limit the paddle to moving at 300 pixels per second and 0.3 * 1000 (1000ms = 1s) == 300.

Making the Ball Move

Making the ball move is similar to the paddle but we’ll be basing the @ball_x and @ball_y changes on @ball_angle using a little basic trigonometry.

If you stretch your mind back to high school, you might recall that we can use sines and cosines to work out the offset of a point at a certain angle within a unit circle. For example, our ball is currently moving at an angle of 45, so:

Math.sin(45 * Math::PI / 180)   # => 0.707106781186547
Math.cos(45 * Math::PI / 180)   # => 0.707106781186548

Note: The * Math::PI / 180 is to convert degrees into radians.

We can use these figures as deltas by which to move our ball based upon a chosen ball speed and the delta time variable that Slick gives us.

Add this code to the end of update:

@ball_x += 0.3 * delta * Math.cos(@ball_angle * Math::PI / 180)
@ball_y -= 0.3 * delta * Math.sin(@ball_angle * Math::PI / 180)

If you run the game now, the ball will move up and right at an angle of 45 degrees, though it will continue past the game edge and never return. We have more logic to do!

Note: We use -= with @ball_y because sines and cosines use regular cartesian coordinates where the y axis goes from bottom to top, not top to bottom as screen coordinates do.

Add some more code to update to deal with ball reflections:

if (@ball_x > container.width - @ball.width) || (@ball_y < 0) || (@ball_x < 0)
  @ball_angle = (@ball_angle + 90) % 360
end

This code is butt ugly and pretty naive (get ready for a nice OO design assignment later) but it’ll do the trick for now. Run the game again and you’ll notice the ball hop through a couple of bounces off of the walls and then off of the bottom of the screen.

Resetting the Game on Failure

When the ball flies off of the bottom of the screen, we want the game to restart. Let’s add this to update:

if @ball_y > container.height
  @paddle_x = 200
  @ball_x = 200
  @ball_y = 200
  @ball_angle = 45
end

It’s pretty naive again, but does the trick. Ideally, we would have a method specifically designed to reset the game environment, but our game is so simple that we’ll stick to the basics.

Paddle and Ball Action

We want our paddle to hit the ball! All we need to do is cram another check into update (poor method – promise to refactor it later!) to get things going:

if @ball_x >= @paddle_x and @ball_x < = (@paddle_x + @paddle.width) and @ball_y.round >= (400 - @ball.height)
  @ball_angle = (@ball_angle + 90) % 360
end

Note: WordPress has borked the less than operator in the code above. Eugh. Fix that by hand 😉

And bingo, we have it. Run the game and give it a go. We have a simple, but performant, video game running on JRuby.

If you’d prefer everything packaged up and ready to go, grab this archive file of my /mygame directory.

What Next?

Object orientation

As I’ve taken pains to note throughout this article, the techniques outlined above for maintaining the ball and paddle are naive – an almost C-esque approach.

Building separate classes to maintain the sprite, position, and the logic associated with them (such as bouncing) will clean up the update method significantly. I leave this as a task for you, dear reader!

Stateful Games

Games typically have multiple states, including menus, game play, levels, high score screens, and so forth. Slick includes a StateBasedGame class to help with this, although you could rig up your own on top of BasicGame if you really wanted to.

The Slick wiki has some great tutorials that go through various elements of the library, including a Tetris clone that uses game states. The tutorials are written in Java, naturally, but the API calls and method names are all directly transferrable (I’ll be writing an article about ‘reading’ Java code for porting to Ruby soon).

Packaging for Distribtion

One of the main reasons I chose JRuby over the Ruby alternatives was the ability to package up games easily in a .jar file for distribution. The Ludum Dare contest involves having other participants judge your game and since most participants are probably not running Ruby, I wanted it to be relatively easy for them to run my game.

Warbler is a handy tool that can produce .jar files from a Ruby app. I’ve only done basic experiments so far but will be writing up an article once I have it all nailed.

Ludum Dare

I was inspired to start looking into JRuby and Java game libraries by the Ludum Dare game development contest. They take place every few months and you get 48 hours to build your own game from scratch. I’m hoping to enter for the first time in just a couple of days and would love to see more Rubyists taking part.

Ruby’s Unary Operators and How to Redefine Their Functionality

Screencast: Coding Conway’s Game of Life in Ruby the TDD Way with RSpec

Recently, there have been many screencasts of people coding things in real time. Yesterday, Ryan Bigg released a video of him implementing Conway’s Game of Life from scratch by reading through the ‘rules’ and then using RSpec to take a test driven approach to fleshing out the functionality.

Ryan is a Ruby Hero and technical writer best known for being co-author of the recently released Rails 3 in Action (along with Yehuda Katz) which I’ll be reviewing soon for Ruby Inside. But Ryan’s also been getting into doing a little screencasting:

If you can’t see the video above, view it directly on Vimeo here.

Ryan’s technique is just one of many legitimate approaches but many of you will find something to pick up from this, especially if you’re not familiar with test driven development or, perhaps, RSpec. If you’re already working on koans non-stop and consider yourself well versed in the ways of TDD, you might want to skip it.

The only downside is that Ryan focuses entirely on the logic without doing a live render of the game board to see his work in action, though this was the right rational choice given the time limit. That would make a good separate project to follow on with, though, if you fancy a little challenge, but be careful to not couple the game logic tightly to any interface you choose to try.

What Ruby’s ||= (Double Pipe / Or Equals) Really Does

In Rubyists Already Use Monadic Patterns, Dave Fayram made a passing reference to using ||= to set a variable’s value if its value were ‘Nothing’ (false or nil in Ruby). The resulting Reddit quickly picked up on his definition (which was fixed later) and argued about ||=‘s true meaning which isn’t as obvious as many Rubyists think. This spread to Freenode’s awesome #ruby-lang IRC channel where I picked it up.

Abstract (or the TLDR Version)

A common misconception is that a ||= b is equivalent to a = a || b, but it behaves like a || a = b

In a = a || b, a is set to something by the statement on every run, whereas with a || a = b, a is only set if a is logically false (i.e. if it’s nil or false) because || is ‘short circuiting’. That is, if the left hand side of the || comparison is true, there’s no need to check the right hand side.

The Common Misconception

a ||= b being equivalent to a = a || b is a popular interpretation for two reasons:

  1. If a and b are both local variables, a = a || b is a short and natural reflection of the outcome.
  2. Other operators like += and -= do operate this way (and this standard dates back to C), e.g.: a += b is equivalent to a = a + b

Do not confuse [op]= with anything related to ||= or &&=. They’re entirely different ideas and are implemented entirely different[ly].

Evan Phoenix (of Rubinius fame)

What’s happening then, if not a = a || b?

A Starter for One

Here’s a simple example of using a ||= b:

a = nil
b = 20
a ||= b
a        # => 20

In this case, a ||= b seems to behave like a = a || b. As mentioned earlier, this is entirely due to a and b both being local variables.

Full Demonstration for Hashes and Arrays

Let’s try something more complicated:

h = {}

def h.[]=(k, v)
  puts "Setting hash key #{k} with #{v.inspect}"
  super
end

# 1. The standard ||= approach
h[:x] ||= 10
h[:x] ||= 20

# 2. The a = a || b approach
h[:y] = h[:y] || 10
h[:y] = h[:y] || 20

# 3. The a || a = b approach
h[:z] || h[:z] = 10
h[:z] || h[:z] = 20

The output:

Setting hash key x with 10
Setting hash key y with 10
Setting hash key y with 10
Setting hash key z with 10

Note that in the first case, using ||=, the hash key’s value is only set once. Once it becomes logically truthful (i.e. anything other than nil or false), h[:x] is no longer assigned any new values, not even itself.

The second case, using the a = a || b approach, does result in two assignments (of the same value). The value remains 10 but the syntax forces h[:y] to assign itself as a value again.

In the last case, the behavior is the same as in the first case, demonstrating that a || a = b is a more realistic notation.

Note: Exactly the same result occurs if we switch the hash for an array and the keys for integers.

Full Demonstration for Getter/Setter Methods

A similar outcome occurs if we’re referring to objects with getter/setter methods (which you may call accessors):

class MyClass
  attr_reader :val

  def val=(val)
    puts "Setting val to #{val.inspect}"
    @val = val
  end
end

# 1. The standard ||= approach
obj = MyClass.new
obj.val ||= 'a'
obj.val ||= 'b'

# 2. The a = a || b approach
obj = MyClass.new
obj.val = obj.val || 'c'
obj.val = obj.val || 'd'

# 3. The a || a = b approach
obj = MyClass.new
obj.val || obj.val = 'e'
obj.val || obj.val = 'f'

And the output shows off similar behavior to the hash and array example:

Setting val to "a"
Setting val to "c"
Setting val to "c"
Setting val to "e"

Default Hash Values: A Sneaky Edge Case?

Our travels don’t end there though. Back in 2008, David Black noticed an edge case with hashes that have default values. If you follow the logic above to the letter, this case will not surprise you, although from a pragmatic point of view, it’s curious.

Let’s take a look:

hsh = Hash.new('default')

hsh[:x]         # => 'default'

# 1. The standard ||= approach
hsh[:x] ||= 10
p hsh           # => {}

# 2. The a = a || b approach
hsh[:y] = hsh[:y] || 10
p hsh           # {:y=>"default"}

# 3. The a || a = b approach
hsh[:z] || hsh[:z] = 10
p hsh           # {:y=>"default"}

Hashes with default values act in an.. interesting way, depending on your point of view. Merely accessing a value doesn’t mean that the value is reified (made concrete) in the hash itself. The reason for this is that you can assign Procs to a hash’s default_proc in order to perform calculations (or even to set values) when an unset key is accessed. It would be undesirable to avoid this behavior merely because a key was accessed earlier on.

Again, we note that the a || a = b-style approach gives the result closest to the reality of ||=.

describe “Conditional operator assignment ‘obj.meth op= expr'” do
it “is equivalent to ‘obj.meth op obj.meth = expr'” do

RubySpec's variables_spec file

Further Reading

This appears to have been a popular discussion point in Rubyland over the years, so I would be remiss not to include links to some of the best references:

And if this tickled your fancy..

Today I’ve opened up tickets for the 3rd and 4th runs of my Ruby Reloaded online Ruby course. It’s aimed at intermediate developers who want to dig deeper, boost their confidence, and bolster their Ruby skill set. We dig into test driven development (TDD), object oriented design, building a library from scratch, code style, and more. It takes place in November and December.

Check out RubyReloaded.com to learn more about the course, what it involves, and when it runs. There are 24 places on each and about half have gone to waiting list folks so far.

P.S. The coupon code INSIDE will give you a $50 discount to thank you for being a Ruby Inside reader!

A MiniTest::Spec Tutorial: Elegant Spec-Style Testing That Comes With Ruby

Despite RSpec‘s awesomeness, Test::Unit remains the most popular Ruby testing tool out there outside of Rails apps. I’ve recently been code walking through a lot of Ruby libraries for my Ruby Reloaded course and the typical arrangement is Test::Unit, sometimes coupled with Shoulda or Contest for some extra syntactic sweetness.

Part of the reason for Test::Unit’s enduring popularity is its presence in the Ruby standard library but, also, its general ‘lightness’ and speed. When you’re writing a large app, using a powerful full-featured system like RSpec has significant benefits (particularly stakeholder involvement in writing the specs). But when you’re working on a library that might spread far and wide and is aimed solely at developers, the pros of Test::Unit shine through.

Enter MiniTest

With Ruby 1.9, however, MiniTest entered the standard library. require 'test/unit' still works in Ruby 1.9 but it’s provided through a compatibility layer on top of MiniTest, so if you’re using require 'test/unit' in Ruby 1.9, you’re really using MiniTest under the hood. It’s possible to switch to using MiniTest::Unit directly without much effort (a few changed assertions and minor additions) but more exciting is the inclusion of MiniTest::Spec, a contextual RSpec-esque syntax, ready to run out of the box with Ruby 1.9.

Note: Ruby 1.8 users can run gem install minitest to get MiniTest too but it’s not part of the standard library there.

What Does MiniTest::Spec Look Like?

Let’s start with a ridiculously simplistic Test::Unit style test:

require 'test/unit'

class TestArray < Test::Unit::TestCase
  def test_array_can_be_created_with_no_arguments
    assert_instance_of Array, Array.new
  end

  def test_array_of_specific_length_can_be_created
    assert_equal 10, Array.new(10).size
  end
end

Nothing too unusual there, I hope. Let’s convert it to MiniTest::Spec:

require 'minitest/spec'
require 'minitest/autorun'

describe Array do
  it "can be created with no arguments" do
    Array.new.must_be_instance_of Array
  end

  it "can be created with a specific size" do
    Array.new(10).size.must_equal 10
  end
end

It’s a matter of style and opinion, of course, but I prefer the latter version. MiniTest::Spec brings RSpec-esque matchers and contexts right into the Ruby 1.9 standard library and I hope it will start to make significant inroads into the library and developer tool test suites, replacing raw Test::Unit.

(For the purists out there, minitest/spec is implemented in a single ~300 line Ruby file. It’s not a framework and it’s easy to walk through the code in 10 minutes. Minimal magic!)

MiniTest::Spec’s Matchers / Expectations

Previously we just did a check for equality and an object’s class, but you’re going to want to go a bit further. Here are MiniTest::Spec’s key expectations:

  • obj.must_be(operator, expected) – for example, 10.must_be :< , 11
  • obj.must_be_close_to – the equivalent of assert_in_delta
  • obj.must_be_empty – Fails unless obj.empty?
  • obj.must_be_instance_of(klass) – Fails unless obj.class == klass
  • obj.must_be_kind_of(klass) – Fails unless obj is of class klass or klass is one of its superclasses.
  • obj.must_be_nil
  • obj.must_be_same_as – tests for true object equality
  • lambda {}.must_be_silent
  • obj.must_be_within_delta
  • obj.must_be_within_epsilon
  • obj.must_equal(other) – Does a ==/eql? comparison between two objects.
  • obj.must_include(other)
  • obj.must_match(regex) – A regular expression match, e.g. "hello".must_match /\w+/
  • lambda {}.must_output(stdout, [stderr..]) – The block should have certain output on stdout or stderr. Set stdout to nil just to check stderr.
  • lambda {}.must_raise(exception)
  • obj.must_respond_to(message)
  • obj.must_throw(sym)

The above are all positive expectations but the opposite ones are easy to build as in most cases you can switch must with wont. For example:

  • wont_be
  • wont_be_empty
  • wont_be_instance_of
  • wont_be_kind_of
  • wont_be_nil
  • wont_be_same_as
  • wont_equal
  • wont_include
  • wont_match
  • wont_respond_to

Note: If you look at the source for minitest/spec.rb you’ll see that the expectations map directly to MiniTest::Unit assertions.

Running MiniTest::Spec Specs In Your Ruby Project / Library

Generally, running MiniTest::Spec tests can use the same mechanisms as you would for Test::Unit tests, so there’s not much to do if you’re already up to speed with T::U.

To get things going with rake just bring rake/testtask into your project’s Rakefile, if it’s not already there, and make some tweaks:

require 'rake/testtask'

Rake::TestTask.new do |t|
  t.libs.push "lib"
  t.test_files = FileList['test/*_test.rb']
  t.verbose = true
end

You’ll want to tweak the glob in FileList when you follow a different convention for filenames (e.g. test/test_*.rb or specs/*_spec.rb). It’s easily updated and gives you rake test for the running.

Give It A Try

So next time you’re starting on a new library and you’re focusing on Ruby 1.9 (it’s about time :-)), give MiniTest::Spec a try. You get a neat testing syntax and it’s all part of the standard library. (If Ruby 1.8 compatibility is still important, of course, you could even just add ‘minitest’ to your Gemfile.)

Further Reading

Peter here! 🙂 I’ve been running an online course called Ruby Reloaded over the past couple of months for intermediate Ruby developers who want to revise the basics and pick up some new tricks. The next run will probably be in October or November so if you want to be on the waiting list or just learn more about the course, click here.

rbenv: A Simple, New Ruby Version Management Tool

rbenv is a new lightweight Ruby version management tool built by Sam Stephenson (of 37signals and Prototype.js fame).

The established leader in the Ruby version management scene is RVM but rbenv is an interesting alternative if you want or need something significantly lighter with fewer features. Think of it as a bit like Sinatra and Rails. It’s not about which is the best, it’s about which is better for you and your current requirements.

What’s the deal with rbenv?

Compared to RVM, rbenv is light. For example, it doesn’t include any mechanism to install Ruby implementations like RVM does. Its sole job is to manage multiple Ruby “environments” and it allows you to quickly switch between Ruby implementations either on a local directory or default ‘system-wide’ basis.

With rbenv, you install Ruby implementations manually or, if you prefer a little help, you can try ruby-build, another project of Sam’s that provides RVM esque recipes for installing seven popular Ruby implementation and version combos.

rbenv primarily works by creating ‘shim’ files in ~/.rbenv/shims which call up the correct version of files for each Ruby implementation behind the scenes. This means ~/.rbenv/shims will be in your path and there’s no threat of incompatibilities between libraries or systems like Bundler and rbenv.

The key thing to be aware of, however, is that if you install a gem that includes ‘binaries’ (or any generally available command line scripts), you need to run rbenv rehash so that rbenv can create the necessary shim files.

How to Install rbenv

Firstly, it’s worth noting that by default rbenv is incompatible with RVM because RVM overrides the gem command with a function. This means to get the full rbenv experience you’ll need to do a rvm implode to wipe away your RVM installation or, at the least, remove/comment out the RVM loader line in your .bash_profile and/or .bashrc.

The installation instructions for rbenv are likely to change fast due to its youth, so I suggest the README. However, rbenv has just been made into a homebrew package on OS X, so if you’re a homebrew user (and if you’re not, check out my screencast), try:

brew update
brew install rbenv
rbenv rehash

And then add this line to your ~/.bash_profile or equivalent:

eval "$(rbenv init -)"

When you open a new shell now, you can run commands like rbenv and rbenv version to see what’s going on. rbenv versions should return nothing since you won’t have any rbenv-enabled Ruby installations yet, so move on to the next step..

Installing Implementations for rbenv

If you have ruby-build installed, getting, say, Ruby 1.9.2-p290 installed is easy:

ruby-build 1.9.2-p290 $HOME/.rbenv/versions/1.9.2-p290

If you prefer to download tarballs and do your own Ruby installs, however, you just need to set the directory prefix at the ./configure stage in most cases. For example:

./configure --prefix=$HOME/.rbenv/versions/1.9.2-p290

Once you’ve installed a new Ruby in this way, you need to run rbenv rehash in order for rbenv to create the ‘shim’ binaries necessary to make the correction version of Ruby available on the path at all times.

The RVM Splashback

In the interests of completeness, it’d be amiss to not mention the minor drama that kicked off on Twitter and Hacker News about rbenv’s release.

rbenv made its way on to Hacker News where, surprisingly, many people railed against RVM. This, coupled with a slightly antagonistic tone taken by rbenv’s README (which has now been taken away), led RVM’s maintainer Wayne E Seguin to vent some pressure on Twitter:

Sam quickly clarified his position:

Nonetheless, Wayne took a little time off, and a campaign to encourage donations to Wayne for his work on RVM was kicked off on Twitter (by Ryan Bates, I believe). The campaign went well, taking RVM’s donations from $7468 to $11370 (at time of writing), a jump of almost $4000 in a few days.

Part of the complaint made in rbenv’s README was about RVM’s “obnoxious” redefinition of the “cd” shell builtin. Essentially, RVM would create a new function which called “cd” but also took into account any .rvmrc files present in each directory so that it could change Ruby version automatically. While there was some validity to this concern, Ben Atkin took some time to write a blog post correcting some of the misinformation on this point.

In the end, however, all seems to be well, and Wayne is already making regular commits to the RVM project again just days later. Hopefully the outpouring of support from the Ruby community for RVM over the past couple of days has shown Wayne that RVM still has a significant user base, most of who aren’t going anywhere new anytime soon. If you want to help out, of course, you can still donate to the RVM Pledgie.

Conclusion

If you’re happy with RVM, there’s not much in rbenv to really leap to. It’s just a lighter and more modular way to achieve the basic functionality that RVM provides while missing out on a lot more (although you can use rbenv-gemset to get some basic gemset-like features).

If, however, you want something “lighter” than RVM, rbenv is certainly worth a look. Its approach feels cleaner and more transparent at a certain level, and if this is of utmost importance to you, you may prefer it. I suspect for the most part, however, RVM’s well-deserved dominance of this area will be maintained.

[ad] Code School is the interactive online marketplace where you can learn to code directly in the browser and the home of the famous “Rails for Zombies” course (which is free to take!) Other courses include Rails Best Practices, jQuery Air: First Flight, and Functional HTML5 & CSS3.

Using Ripper to See How Ruby Is Parsing Your Code

In the past couple of months I’ve seen situations arise where developers aren’t entirely sure how Ruby has chosen to interpret their code. Luckily, Ruby 1.9 comes with a built-in library called Ripper that can help solve the problem (there’s a 1.8 version too, see later). Here, I give the 30 second rundown on what to do.

A Mystery To Solve

I’ve seen this confusion appear twice in the last month (the second time was what inspired me to write this post):

> puts {}.class

 => NilClass

Despite thinking that we should be seeing Hash appear, we don’t. We get a blank line and NilClass in response. It doesn’t get any better if you start prodding:

> puts { :x => 10 }.class
SyntaxError: (irb):19: syntax error, unexpected tASSOC, expecting '}'

What!?

Thankfully, you don’t need to wonder any more. Even if you can have a good guess at what’s going on, it’s possible to lean on Ripper to figure things out.

What is Ripper?

Ripper is a library introduced in MRI Ruby 1.9 that hooks directly into Ruby 1.9’s parser and which can provide you with abstract syntax trees or simple lexical analysis of the code that you provide. This can be useful to work out why Ruby is interpreting a given piece of code in a certain way, such as our troublemaker above.

The following tip isn’t going to be a full breakdown of what Ripper does, of course, but there are already posts out there to help with that. Check out Using Ruby 1.9 Ripper by Sven Fuchs for starters.

How to Solve Our Mystery

So what is puts {}.class up to?

Getting Ripper to give us its interpretation of events (and therefore the interpretation of what Ruby 1.9 is seeing when it parses the code) is easy:

p Ripper.sexp("puts {}.class")

[:program, [[:call, [:method_add_block, [:method_add_arg, [:fcall, [:@ident, "puts", [1, 0]]], []], [:brace_block, nil, [[:void_stmt]]]], :".", [:@ident, "class", [1, 8]]]]]

Not exactly the easiest thing in the world to read, so I suggest you gem install awesome_print (see our writeup on why it’s so awesome) and then try:

require 'ap'
ap Ripper.sexp("puts {}.class")

[
    [0] :program,
    [1] [
        [0] [
            [0] :call,
            [1] [
                [0] :method_add_block,
                [1] [
                    [0] :method_add_arg,
                    [1] [
                        [0] :fcall,
                        [1] [
                            [0] :@ident,
                            [1] "puts",
                            [2] [
                                [0] 1,
                                [1] 0
                            ]
                        ]
                    ],
                    [2] []
                ],
                [2] [
                    [0] :brace_block,
                    [1] nil,
                    [2] [
                        [0] [
                            [0] :void_stmt
                        ]
                    ]
                ]
            ],
            [2] :".",
            [3] [
                [0] :@ident,
                [1] "class",
                [2] [
                    [0] 1,
                    [1] 8
                ]
            ]
        ]
    ]
]

There are very few people who will be ready to confidently interpret this output out of the box, but if we pick through it we can get some significant clues as to what’s going on. It is important to keep track of the nesting.

Note that the first nested section starts with :call and then has some nested sections starting with :method_add_block and :brace_block. A function call (fcall) to puts is then associated with that block. Later on, . (to call a method/send a message) is invoked, and then the "class" message passed upon that block. So what’s happening?

It turns out that Ruby is interpreting the {} as a code block being used upon puts! It’s not a hash, but a code block! If you rewrite the code a little to remove the ambiguity and try again, what happens?

ap Ripper.sexp("puts({}.class)")
[
    [0] :program,
    [1] [
        [0] [
            [0] :method_add_arg,
            [1] [
                [0] :fcall,
                [1] [
                    [0] :@ident,
                    [1] "puts",
                    [2] [
                        [0] 1,
                        [1] 0
                    ]
                ]
            ],
            [2] [
                [0] :arg_paren,
                [1] [
                    [0] :args_add_block,
                    [1] [
                        [0] [
                            [0] :call,
                            [1] [
                                [0] :hash,
                                [1] nil
                            ],
                            [2] :".",
                            [3] [
                                [0] :@ident,
                                [1] "class",
                                [2] [
                                    [0] 1,
                                    [1] 8
                                ]
                            ]
                        ]
                    ],
                    [2] false
                ]
            ]
        ]
    ]
]

It should be immediately apparent once you walk through this syntax tree array that things are now good. In the second nested section you should be able to make out a :call section whose first argument is a :hash, then the ., and then the class message. This means we have a hash upon which the class method is being called – the behavior we wanted 🙂

Needless to say, it can get more complicated than that, and syntax trees can get significantly deeper too, but if you get stuck on an obscure parsing error or simply want to dig into what Ruby is up to when it’s parsing your code, give Ripper a quick spin.

But I’m on Ruby 1.8!

Despite being a Ruby 1.9ism, Ripper has been ported to Ruby 1.8 by Loren Segal. He has also written a blog post about it. I’ve not tried it (I’m a fully paid up 1.9 guy nowadays) but it’s worth a try if you’re still using 1.8.

Bonus Info

Sorcerer is a library by Jim Weirich that can turn the s-expressions above back into Ruby code. This could be useful for changing Ruby code in a structured way. I only had limited success with it though on some simple examples. Still, worth looking into.

Careful Cutting To Get Faster RSpec Runs with Rails

A few months ago, Ruby Inside wrote about using Spork with RSpec 2 and Rails 3 in order to get a more sprightly spec run. Unfortunately, using the techniques in the article with our fledgling codebase’s test suite left us with somewhat disappointing results, so I decided to dig deeper and see if I could do better.

Note: This is a guest post by Jon Frisby of Cloudability. See the post footer for more info.

With and Without Spork

First, let’s see what things look like with and without Spork running on our raw test suite.

Note: The machine I’m using is a spanking-new 15″ MacBook Pro with the 2.2Ghz quad i7 and running Ruby 1.9.2-p180.

“time rspec spec” without Spork running:

Finished in 15.78 seconds
75 examples

real    0m22.334s
user    0m17.952s
sys     0m2.643s

We can see that we’re not overly I/O bound (real vs. user+sys), but we are spending a LOT of time doing “real work”. Ugh.

“time rspec spec” with Spork running:

Finished in 16.82 seconds
75 examples

real    0m17.340s
user    0m0.214s
sys   0m0.065s

This didn’t exactly equate to a big boost! (Editor notes: Most of Spork’s win is in running specs over and over rather than once-off speed, but I’ll let this slide for now ;-)) Just for clarity, here’s our barebones spec_helper.rb file showing what runs in the prefork as well as on each further run:

require 'spork'

Spork.prefork do
  ENV["RAILS_ENV"] ||= 'test'
  require File.expand_path("../../config/environment", __FILE__)
  require 'rspec/rails'

  RSpec.configure do |config|
    config.mock_with :rspec
    config.use_transactional_fixtures = true
  end
end

Spork.each_run do
  # This code will be run each time you run your specs.
  Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}
end

Cutting out MySQL

So, where are we spending out time and what can we do about it? First I’ll try cutting MySQL out of the picture and use an in-memory SQLite DB for our tests. This article was a helpful starting point for me, but I discovered quickly that the spec_helper.rb addition needed must be placed in the Spork.each_run block – not the Spork.prefork block.

Unfortunately, the silence_stream call winds up being superfluous because Spork has captured it already, and ActiveRecord isn’t writing to STDOUT anymore. This will make the tests a bit noisier when the Spork server is running, but that’s not a huge deal.

Our spec_helper.rb file’s each_run section now becomes this:

Spork.each_run do
  # This code will be run each time you run your specs.
  load_schema = lambda {
    load "#{Rails.root.to_s}/db/schema.rb" # use db agnostic schema by default
    # ActiveRecord::Migrator.up('db/migrate') # use migrations
  }
  silence_stream(STDOUT, &#038;load_schema)

  Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}
end

“time rspec spec” without Spork running:

Finished in 14.95 seconds
75 examples

real    0m21.866s
user    0m17.826s
sys   0m2.688s

A little bit better – and every win helps – but not huge. Let’s see how things look with the Spork server running.

“time rspec spec” with Spork running:

Finished in 14.83 seconds
75 examples

real    0m15.504s
user    0m0.222s
sys 0m0.064s

Things are beginning to look a bit better, but there is still room for improvement.

Cutting out Garbage Collection

The most obvious candidate is garbage collection. Turning off GC outright makes things faster, but at an unacceptable cost: The spec runner bloats from a peak of 81MB to a peak of 418MB. It turns out though that we can make a bit of a trade-off here by explicitly running GC periodically and finding a sweet-spot between too much time spent in GC and too much memory growth.

Our new spec_helper.rb disables GC in general, and forces a run after every 10th test. I didn’t go for an exhaustive analysis of the time/space tradeoff here, but converged to this as a “good enough” option after a handful of tests.

Here’s the new spec_helper.rb file (a lot more changes this time):

Spork.prefork do
  # Loading more in this block will cause your tests to run faster. However,
  # if you change any configuration or code from libraries loaded here, you'll
  # need to restart spork for it take effect.
  ENV["RAILS_ENV"] ||= 'test'
  require File.expand_path("../../config/environment", __FILE__)
  require 'rspec/rails'

  counter = -1
  RSpec.configure do |config|
    config.mock_with :rspec
    config.use_transactional_fixtures = true

    config.after(:each) do
      counter += 1
      if counter > 9
        GC.enable
        GC.start
        GC.disable
        counter = 0
      end
    end

    config.after(:suite) do
      counter = 0
    end
  end
end

Spork.each_run do
  GC.disable

  # From: http://www.osmonov.com/2011/01/in-memory-sqlite-database-for-testing.html
  load_schema = lambda {
    load "#{Rails.root.to_s}/db/schema.rb" # use db agnostic schema by default
    # ActiveRecord::Migrator.up('db/migrate') # use migrations
  }
  silence_stream(STDOUT, &#038;load_schema)

  Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}
end

“time rspec spec” without Spork running:

Finished in 14.78 seconds
75 examples

real    0m21.384s
user    0m16.421s
sys   0m2.830s

“time rspec spec” with Spork running:

Finished in 13.36 seconds
75 examples

real    0m13.981s
user    0m0.218s
sys   0m0.061s

These runs used 145MB and 142MB of memory respectively. A considerable increase in memory, but not bad given the time win for controlling our GC behavior. The tradeoff time-wise (versus just disabling GC) turns out to be small — about half a second. I can live with that.

But all we’ve really been doing so far is shaving off some rough corners. We haven’t addressed the real issue head-on — the 13+ seconds of “real work” being done.

Taming Devise

My next step was to bust out perftools.rb and do some for-real profiling. I’m going to get a bit hand-wavy, cut to the chase and tell you what I found to be the single biggest culprit: Devise.

As with many in Rails-land, we’re using Devise to implement our user account and authentication functionality. Devise utilizes a “work factor” mechanism to make the computational cost of computing a password hash relatively high. This is to make brute-forcing the system that much harder for potential attackers, and it’s a very important mechanism.

Most of our models have an association to our User class, and we’re using the Devise-recommended choice of bcrypt with the default 10 stretches for hashing passwords right now. Obviously, anything that involves creating users is going to add up relatively fast. In hind-sight, this should have been fairly obvious. D’oh.

So, what do we do in test-mode? In test-mode we don’t care is the test data includes easy-to-brute-force passwords. We can’t just set stretches to 0, because bcrypt won’t let us. One little monkey-patch to Devise later, and we can get past that!

Our updated spec_helper.rb has an extended Spork.prefork section:

Spork.prefork do
  # Loading more in this block will cause your tests to run faster. However,
  # if you change any configuration or code from libraries loaded here, you'll
  # need to restart spork for it take effect.
  ENV["RAILS_ENV"] ||= 'test'
  require File.expand_path("../../config/environment", __FILE__)
  require 'rspec/rails'

  # Don't need passwords in test DB to be secure, but we would like 'em to be
  # fast -- and the stretches mechanism is intended to make passwords
  # computationally expensive.
  module Devise
    module Models
      module DatabaseAuthenticatable
        protected

        def password_digest(password)
          password
        end
      end
    end
  end
  Devise.setup do |config|
    config.stretches = 0
  end

  counter = -1
  RSpec.configure do |config|
    config.mock_with :rspec
    config.use_transactional_fixtures = true

    config.after(:each) do
      counter += 1
      if counter > 9
        GC.enable
        GC.start
        GC.disable
        counter = 0
      end
    end

    config.after(:suite) do
      counter = 0
    end
  end
end

“time rspec spec” without Spork running:

Finished in 6.34 seconds
75 examples

real    0m12.982s
user    0m9.567s
sys   0m2.699s

“time rspec spec” with Spork running:

Finished in 6.32 seconds
75 examples

real    0m6.935s
user    0m0.219s
sys   0m0.058s

Bingo. So now we’ve gone from around 17s to around 7s. And that is how you make your specs faster.

While Spork can make multiple runs faster, it’s not the be-all and end-all of making your spec runs faster generally, so see if there are other wins to be had as well.

Jon Frisby is a jack-of-all-trades coder and is currently the co-founder of Cloudability, which aims to be the Mint.com for cloud spending. He’s a veteran of the startup world and even after being co-founder or founder of 4 companies, he insists that he still has some of his sanity left.

How to Install and Use Postgres On OS X For Ruby and Rails Development

I hang out in #nwrug on Freenode, the IRC channel of a Ruby user group here in the UK, and floated the idea of doing a PostgreSQL (a.k.a. Postgres) installation tutorial for Ruby Inside. Coincidentally, it turned out 37signals sysadmin Will Jessop was already working on one so, I present.. Setting up PostgreSQL for Ruby on Rails development on OS X by Will Jessop 🙂

The Article..

Will’s post is a walkthrough of the process from sitting at an empty terminal prompt through to having a barebones Rails 3 app running on a Postgres powered database. It’s entirely Mac OS X focused, so don’t expect to enjoy it too much if you’re on Linux or Windows!

Will covers:

  • installation (super simple with Homebrew)
  • start/stop controls for OS X
  • initialization
  • user creation
  • database setup
  • installing the pg gem

Or, the Screencast!

I still wanted to bring something to the table despite Will’s work so I asked if I could make a screencast that roughly followed the same lines as his tutorial and he was up for it. So, I present, a scrappy 13 minute video alternative to the above tutorial:

My walkthrough is somewhat different. I spend a couple of minutes explaining what Postgres is, in case you’re not familiar with it, and I use Mike Perham’s awesome launchctl controller Lunchy to manage the starting and stopping of Postgres instead of the usual (and arcane) Apple tools. I also make references to Rebecca Black and Mister Mister.

While preparing for this post, I’ve found a lot of small, useful Ruby libraries that improve the Postgres experience. I’m collecting those together and will be posting with a grab-bag of useful links soon.

How to Play with Rails 3.1, CoffeeScript and All That Jazz Right Now

Maybe I’m weird (actually, there’s no maybe about it) but when I first heard about Rails 3.1 getting CoffeeScript and Sass out of the box, I wanted to see how it worked and how smooth the process would be. So like quite a few people on IRC I’ve seen, I installed edge Rails (currently 3.1.0-beta) and got playing. (Yes, it’s PRE-RELEASE. Expect mischief!)

I hit a couple of stumbling blocks on my way so I thought I’d explain what I found to be the smoothest way through to getting to play with the new Rails 3.1 goodies. I’ll only take you as far as making some changes and seeing the results, though – you’re on your own from there!

Note: This post was written in April 2011. If you are reading much later on, much of this post may no longer be relevant and you should refer to guides about installing the eventual full release of Rails 3.1 instead. If I remember, I’ll update this to reflect that 😉

Installing Edge Rails (Rails 3.1 Beta)

Being a conservative kinda dude with the versions of things I run, I hadn’t run the edge Rails gauntlet for some time. I naively tried rails new myapp --edge and while it appeared to work and installed edge Rails, there be dragons (that even rake rails:update couldn’t slay). So do it this way instead:

  • Head to whatever directory you use as the base for all of your git cloning. I’ll assume ~/code from here on out.
  • Clone the Rails repository from GitHub with:
    git clone git://github.com/rails/rails.git
    

Creating a Bare Rails 3.1 App

Cloning edge Rails was the easy bit. Now let’s create an app with the bad boy:

  • Head to whatever directory you want to use as the base for your Rails projects. I’ll assume you remain in ~/code.
  • Create a new Rails app with:
    ~/code/rails/bin/rails new yourapp --edge
    

    It’s important to note that we’re explicitly calling the rails script that’s in the edge Rails git repository we just cloned. And, of course, you can call the app whatever you like but I find yourapp to be both unique and catchy.

  • Enjoy watching your Rails app being created and waiting for Bundler to finish its work grabbing edge versions of all sorts of things.
  • Dive into your app’s folder:
    cd yourapp
    
  • Check everything went OK so far by running:
    rails server
    
  • Browse to http://localhost:3000/ (or whatever is relevant in your case) and ensuring you get the usual Rails welcome page.
  • CTRL+C your way out of rails server and get back to the prompt.

We have a working but dead boring Rails 3.1 app on our hands. Let’s get something happening and see what Rails 3.1 is rocking in the CoffeeScript and Sass departments.

In the interests of having something running as soon as possible, we’ll lean on the scaffold generator to get some default, core team approved model, controller, and view code up and running. Simply:

rails generate scaffold Link title:string url:string slug:string visits:integer

Yes, it’s an example model for a URL shortener (the new “hello world” or “blog in 15 minutes” project)! That doesn’t matter though – you can do whatever you like.

Don’t forget to run:

rake db:migrate

I did 😉

Sprockets – Asset Packaging Shenanigans!

Run rails server again now and browse to http://localhost:3000/links/ – pretty typical scaffolding fare, right?

View the source though and check out the <head> section:

If you dig into application.js and application.css (as they’re being served up by the server), you’ll notice that they’re a bit different to the same files in older Rails apps. They contain JavaScript code and CSS code respectively but if you look through the /public folder in your app, those files are nowhere to be found. Shenanigans!

Or not. Sprockets is merely at play, melting and merging down multiple CSS and JavaScript files into a single gooey lump to send to your Web browser.

Playing “Hunt The JavaScript and CSS”

We’re getting CSS and JavaScript being served up through application.css and application.js just fine then, but where are they coming from? Here’s a clue!

Oh yes, there’s a app/assets folder and its beautiful children javascripts and stylesheets. It seems these two fine specimens will become our friends when we make the transition to Rails 3.1.

You may notice that my file tree doesn’t look quite the same as yours. That’s because I’ve already started playing with CoffeeScript and Sass by creating an app/assets/javascripts/awesome.js.coffee file and a app/assets/stylesheets/scaffold.css.scss file (the latter just being a rename of the scaffold.css file you already have).

If you take a sneaky peek into application.css you’ll notice there’s not really any CSS in there. Merely a comment with a directive like so:

/*
 * FIXME: Introduce SCSS & Sprockets
 *= require_tree .
*/

require_tree is just telling the system to bundle together everything from the stylesheets folder into a single file. Awesome – thanks Sprockets!

Playing with Sass

To have a play with Sass first, rename scaffold.css to scaffold.css.scss. If you then reload the /links page in your Web browser you’ll notice little difference. Why? Because Sass (or, more specifically, SCSS) is merely a superset of CSS and any existing CSS will work with it!

Open up scaffold.css.scss and you’ll see it’s pretty boring. It’s just the standard stuff that comes with Rails after all. The first section looks something like this:

body { background-color: #fff; color: #333; }

Let’s say we want to keep our background and text colors in variables so we can use them throughout our CSS later (meaning we only have to change a couple of variables instead of hundreds of references if we want to retheme our app). Rewrite the previous section to:

$background_color: #fee;
$text_color: #000;

body { background-color: $background_color; color: $text_color; }

Here I’ve assigned the colors to variables and then use the variables in the CSS. I’ve made some minor changes to the colors too so that I can definitely see a difference when I reload the page in my browser.

And, well, that’s it. That’s the absolute bare basics of using SCSS in Rails 3.1. Dead simple. Stick .scss on the end of a filename to trigger the SCSS/SASS parser and you’re cooking with gas.

Playing with CoffeeScript

At the time of writing, the application.js file is a wee bit broken as it has a comment that’s not being parsed out. Since this stuff was only added on the very day I wrote this post, I’ll let them off. But in case it’s broken for you still, get application.js looking like this:

#= require jquery
#= require jquery_ujs
#= require_tree .

These directives should remind you of the equivalent in application.css. As with there, they include other JavaScript files into application.js when it’s served up. You get jQuery, the “unobstrusive” jQuery helpers for Rails, and any other files in the javascripts folder (currently none).

To give CoffeeScript a try, create a file called awesome.js.coffee in the app/assets/javascripts folder and populate it thus:

square = (x) -> x * x
alert square(10)

If you refresh the http://localhost:3000/links/ page again now, you’ll have an annoying JavaScript alert window popping up with “100” in it (the result of square(10)).

This isn’t the time or place to dig into what CoffeeScript does or how it works but.. you’ve just played with it nonetheless 😉 If you want to learn more about it, its official homepage is packed with useful stuff.

Like the street walker I picked up solely to use the car pool lane, I’m going to dump you off at the curb here in the middle of conversation. It’s been fun. Good luck and have fun breaking Rails 3.1. If you find any really nasty bugs, be sure to either raise a ticket so the lovely Rails developers can make Rails 3.1 even better or, y’know, submit a patch yourself.

Want to show some appreciation after this lovely blog post? Check out the Ruby Weekly and JavaScript Weekly e-mail newsletters or pass them on to your buddies or co-workers. People are loving them and they’re doing great but the more the merrier!

How To Get Rails 3 and RSpec 2 Running Specs Fast (From Scratch)

Rails 3 is great. RSpec 2 is great. And Ruby 1.9.2 is really great. Getting them all running together and quickly, however, isn’t entirely straightforward. In this post I demonstrate how to get everything ticking over along with automatically running, super-snappy test runs.

The ultimate outcome is using Ruby 1.9.2 (though much of this is relevant to 1.8 still) to create a Rails 3 app, hook up RSpec 2, and be able to run specs quickly. The first two parts are easy(ish) but the “quickly” part requires some tinkering. Grab a coffee and carry on..

Create a new Rails 3 app

Got Rails 3 installed? If not, gem install rails will see you good. Then head on down to your favorite project folder with your shell and create a new Rails 3 app like so:

rails new myapp --skip-test-unit

You can retroactively bring RSpec 2 into an existing Rails 3 project, of course, but it’s easier for this walkthrough to start afresh in case of application-specific issues.

Hooking up RSpec 2 with RSpec-Rails

Edit the Gemfile file in your new Rails project (myapp/Gemfile in this example) and add the following block to the bottom:

group :development, :test do
  gem 'rspec-rails'
end

This tells Bundler (a gem management and dependency tool Rails 3 likes to lean on) we want to use the rspec-rails gem which will get RSpec running with Rails 3.0 for us. Next, we get Bundler to do its thing:

bundle

This will install all of the gems referenced in Gemfile, including rspec-rails. (You can use bundle install instead, if you prefer, but bundle on its own works too.)

Last but not least, we need to run RSpec’s ‘generator’ that rspec-rails has put in place for us:

rails generate rspec:install

The generator creates a few files. Namely:

  • .rspec – a config file where we can store extra command line options for the rspec command line tool. By default it contains --colour which turns on colored output from RSpec.
  • spec – a directory that will store all of the various model, controller, view, acceptance and other specs for your app
  • spec/spec_helper.rb – a file that’s loaded by every spec (not in any automatic way but most have require 'spec_helper' at the top). It sets the test environment, contains app level RSpec configuration items, loads support files, and more.

We still can’t run rake and see anything interesting yet because we don’t have a database or any models initialized.

Creating a model to test

Let’s take the easy way out and use the scaffold generator to flesh out something for us to test (as well as to see what spec files can be generated automatically):

rails generate scaffold Person name:string age:integer zipcode:string

It’s worth noting that when you generate the scaffold numerous spec files are also created (thanks to rspec-rails):

spec/models/person_spec.rb
spec/controllers/people_controller_spec.rb
spec/views/people/edit.html.erb_spec.rb
spec/views/people/index.html.erb_spec.rb
spec/views/people/new.html.erb_spec.rb
spec/views/people/show.html.erb_spec.rb
spec/helpers/people_helper_spec.rb
spec/routing/people_routing_spec.rb
spec/requests/people_spec.rb

Now bring the database up to speed with the migration for the new model:

rake db:migrate

Now let’s run rake – finally! The result:

...............**............

Pending:
  PeopleHelper add some examples to (or delete) /Users/peter/dev/rails/myapp/spec/helpers/people_helper_spec.rb
    # Not Yet Implemented
    # ./spec/helpers/people_helper_spec.rb:14
  Person add some examples to (or delete) /Users/peter/dev/rails/myapp/spec/models/person_spec.rb
    # Not Yet Implemented
    # ./spec/models/person_spec.rb:4

Finished in 0.31043 seconds
29 examples, 0 failures, 2 pending

Rock and roll. We’re up and running. Sort of. Let’s put in some “real” specs to be sure things are working nicely.

Change spec/models/person_spec.rb to the following rather contrived pair of specs:

require 'spec_helper'

describe Person do
  it "can be instantiated" do
    Person.new.should be_an_instance_of(Person)
  end

  it "can be saved successfully" do
    Person.create.should be_persisted
  end
end

Not the most useful things to spec out, admittedly, but you get a little database action and get rid of a pending spec we had cluttering things up. We haven’t got anything else we can seriously test yet anyway.

Now let’s run rake spec:models to focus our efforts on what we’ve just done:

..

Finished in 0.09378 seconds
2 examples, 0 failures

How to have specs run automatically with Watchr

Let’s assume we’ve progressed with developing our app and we’re working on models and controllers, testing along the way. Rather than running rake or bundle exec rspec all of the time, wouldn’t it be great to have the relevant spec run automatically when we either edit the spec or a model/controller that has a spec? Well, with watchr, we can. (Note: Some people prefer autotest. I find watchr more flexible and useful for other things beyond just running specs.)

But if you really want to use autotest, Mike Bethany explains how to set it up in a similar scenario in a post of his own, along with autotest-growl for OS X notifications.

Add watchr to your Gemfile‘s testing and production gem section:

group :development, :test do
  gem 'rspec-rails'
  gem 'watchr'
end

Then run bundle to install it.

Next, create a file called .watchr in your app’s root folder and populate it with this code:

def run_spec(file)
  unless File.exist?(file)
    puts "#{file} does not exist"
    return
  end

  puts "Running #{file}"
  system "bundle exec rspec #{file}"
  puts
end

watch("spec/.*/*_spec\.rb") do |match|
  run_spec match[0]
end

watch("app/(.*/.*)\.rb") do |match|
  run_spec %{spec/#{match[1]}_spec.rb}
end

This ‘watchr script’ directs a running watchr process to do a few things:

  • If any file ending in _spec.rb under the spec/ directory changes, run the run_spec method with its filename.
  • If any .rb file under the app/ directory changes, call the run_spec method with an equivalently named _spec.rb file under spec.
  • run_file accepts a filename for a spec file, checks it exists, and tells the system to run it (using system)

If you now run watchr .watchr to use the .watchr script, not much will happen. But if you make any change (or even just re-save) to, say, spec/models/person_spec.rb, that spec will run automatically. Make a change to app/models/person.rb and it’s the same deal. To stop watchr, CTRL+C saves the day.

Watchr can be used for a lot more than this but this is just for starters 😉

Optionally, you might also like to create lib/tasks/watchr.rake and include the following code so you can just remember to run rake watchr instead (it’s nice to have anything you run within a project contained in one place):

desc "Run watchr"
task :watchr do
  sh %{bundle exec watchr .watchr}
end

How to get faster spec runs with Spork

We’ve got Rails 3 running with RSpec 2 and watchr’s giving us some automatically-running-spec love. But do you notice how slow it is? Specs run quickly once they’re loaded but there are several seconds of waiting beforehand.

If you run time rake spec:models with Ruby 1.9.2, you’ll probably see a wallclock time of over 5 seconds (5.204s on my machine and I’m SSDed up) – holy splingledoops! If not, you’re lucky, but it’s a commonly reported problem with some improvements expected in Ruby 1.9.3. We can’t wait that long though..

Enter Spork. Spork is a tool that loads the Rails environment and then forks each time you want to run some specs (or tests, it can be set up to run with Test::Unit too). In this way, the whole Rails initialization process is skipped, shaving valuable seconds off of your spec runs.

Edit your Gemfile again and include Spork:

gem 'spork', '~> 0.9.0.rc'

Run bundle to install Spork.

Next, Spork needs to make some changes to your spec/spec_helper.rb file. Because it only initializes the Rails environment once and then forks it, you might have initialization features that you need to run on each test run. Spork will let you do this but it needs to make those changes first. Run:

spork --bootstrap

The result:

Using RSpec
Bootstrapping /Users/peter/dev/rails/myapp/spec/spec_helper.rb.
Done. Edit /Users/peter/dev/rails/myapp/spec/spec_helper.rb now with your favorite text editor and follow the instructions.

Bring up spec/spec_helper.rb. All spork --bootstrap has done is add some extra code to the top of the file. Read the comments there to get a better feel for what to do and what Spork requires and keep them in mind as we progress (in case you want to do something differently).

Get rid of require 'rubygems' from the first line – we’re using Bundler so it’s not necessary.

Next, cut and paste all of the ‘old’ contents of spec_helper.rb into the Spork.prefork block. Since we’re running an empty(ish) project, there’s nothing special we’ve added that we need to run on each run using the Spork.each_run block. We can leave that empty.

You’ll end up with a spec_helper.rb file that looks like this:

require 'spork'

Spork.prefork do
  # Loading more in this block will cause your tests to run faster. However, 
  # if you change any configuration or code from libraries loaded here, you'll
  # need to restart spork for it take effect.
  # This file is copied to spec/ when you run 'rails generate rspec:install'
  ENV["RAILS_ENV"] ||= 'test'
  require File.expand_path("../../config/environment", __FILE__)
  require 'rspec/rails'

  # Requires supporting ruby files with custom matchers and macros, etc,
  # in spec/support/ and its subdirectories.
  Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}

  RSpec.configure do |config|
    # == Mock Framework
    #
    # If you prefer to use mocha, flexmock or RR, uncomment the appropriate line:
    #
    # config.mock_with :mocha
    # config.mock_with :flexmock
    # config.mock_with :rr
    config.mock_with :rspec

    # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
    config.fixture_path = "#{::Rails.root}/spec/fixtures"

    # If you're not using ActiveRecord, or you'd prefer not to run each of your
    # examples within a transaction, remove the following line or assign false
    # instead of true.
    config.use_transactional_fixtures = true
  end
end

Spork.each_run do
  # This code will be run each time you run your specs.
end

Head back to your shell and the root of your project and run spork:

Using RSpec
Loading Spork.prefork block...
Spork is ready and listening on 8989!

Now we’re cooking with gas. Open another shell, head to the root of your project, and run watchr .watchr too. Then head to spec/models/person_spec.rb in your text editor and re-save it (or even make a change if you want). Your specs run but.. they’re no faster! What’s wrong?

It turns out we need to make another change so that RSpec knows we’re running Spork. Edit the .rspec file (mentioned earlier) and add --drb to the line (so it probably reads --colour --drb). Now, edit the spec again, save, and.. fast!

You should note that if you use rake at this point to run your entire suite, it’ll still not be particularly fast because rake itself is initializing Rails in order to do its job. But if you want to run your entire suite quickly, just run:

rspec spec

With our dummy app and on my machine, this runs in a wallclock time of 0.759s – a serious improvement over 5.2 seconds.

We have Rails 3, RSpec 2, watchr, spork, and SUPER-DUPER FAST SPECS all running on Ruby 1.9.2. Score!

A minor snafu will remain, though. If you update app/models/person.rb, the change won’t take effect in your tests since Spork has the old Person still in memory. One way around this is to edit config/environments/test.rb and change:

config.cache_classes = true

To:

config.cache_classes = false

Now your app’s classes are reloaded when necessary.

How to Install Ruby 1.9.2 and Rails 3.0 on Ubuntu 10.10

For better or worse, Ubuntu has become one of the most popular Linux variants on which to deploy Ruby and Rails apps. It was used for 84% of the 2010 Rails Rumble projects, for example. Back in 2009, I wrote a guide to installing a Ruby 1.8 stack on Ubuntu 8.10 so it was only a matter of time before I had to tackle 10.10 (Maverick Meerkat) and Ruby 1.9.

A few days ago I needed to produce a screencast on installing Ruby 1.9.2 on Ubuntu 10.10 for students in my forthcoming Ruby class to use. It was a pleasant surprise, then, to discover that Ryan Bigg had posted Ubuntu, Ruby, RVM, Rails and You on Christmas Day. It’s a written walkthrough of installing Ruby 1.9.2 and Rails 3.0 on Ubuntu 10.10. So if you want a written walkthrough, read his post.

I still needed a screencast though so I compared Ryan’s technique to mine, made some minor tweaks, and followed his general process when making the following screencast. So if you prefer screencasts to blog posts, you’re in luck. The video is available on YouTube as “How to Install Ruby 1.9.2 and Rails 3.0 on Ubuntu 10.10” or if you’re on the Web, you can see it embedded below:

Errata: 1) The aspect ratio for the video is wrong. I don’t tend to do HD uploads so I learned a lesson there. This doesn’t affect the content, though. 2) I call Ryan Bigg “Ryan Biggs” once or twice. Curiously this seems to be a common mistake on Ruby blogs..

PeepCode Releases The “Meet Rails 3″ Screencast Series

meet-rails-3.png Ruby screencasting supremo Geoffrey Grosenbach has unveiled PeepCode’s new Meet Rails 3 series. There are two parts so far, clocking in at 75 and 92 minutes respectively – they’re $12 each or “free” if you have a PeepCode Unlimited subscription.

Geoffrey has pulled out all of the stops to produce his slickest and best produced screencasts yet. Striking effects abound and he’s perfected the art of producing memorable yet straightforward diagrams to demonstrate the points he makes. This is a great way to get onto the Rails 3 wagon if you haven’t yet tried.

Straight from the horse’s mouth:

The “Meet Rails 3” series is for anyone who is comfortable with any programming language, but wants to learn Ruby on Rails. It starts with a brief introduction to the Ruby language and adds a gentle tutorial on the basic concepts of Rails 3. Part II surges forward with models, views, and controllers to build a simple but stylish project management application.

As always, both videos reflect hours and hours of attention to the details, useful tips and tricks, and brand new visuals developed specifically for this series. Our previous series for Rails 1 and 2 were what made PeepCode viable as a business and this series has already started selling at a steady clip as well.

Geoffrey Grosenbach

He also notes that PeepCode is also selling Jeremy McAnally’s fine “Rails 3 Upgrade Handbook” which we reviewed on Rails Inside a while back.

But there’s another option too – if you’d prefer a 15+ hour compendium of screencasts with an “over the shoulder” perspective of every part of developing multiple Rails 3 apps, as well as an e-book covering the same material, check out Michael Hartl’s similarly awesome RailsTutorial.org (which we reviewed here). It’s not directly comparable to Geoffrey’s work but might suit some people better. Options are always good!

Rails for Zombies: An Online Rails Learning Environment

railszombies.pngRails for Zombies is an intriguing attempt to teach people how to use Ruby on Rails directly in the Web browser. It comes from Envy Labs (and specifically Gregg Pollack, once of RailsEnvy fame).

The goal of Rails for Zombies is to make the learning process immediately accessible and fun. You’re guaranteed to learn quite a bit too as the in-browser development environment frequently tests you and makes you actually do stuff rather than merely read learning material.

As Gregg points out, what you learn through R4Z won’t be quite enough for you to build your own version of Twitter (or even Twitter for zombies – arf arf) but it covers enough of the basics to put you in a better position to continue with more traditional learning techniques later.

[suggestion] You know I launched Ruby Weekly, a weekly Ruby e-mail newsletter? Well, last week I launched JavaScript Weekly for all of you JS-heads too! It’s been going great and the next issue is out later today.

Writing Parsers in Ruby using Treetop

treetop.pngTreetop is one of the most underrated, yet powerful, Ruby libraries out there. If you want to write a parser, it kicks ass. The only problem is unless you’re into reading up about and playing with parsers, it’s not always obvious how to get going with them, or Treetop in particular. Luckily Aaron Gough, Toronto-based Ruby developer, comes to our rescue with some great blog posts.

Aaron, who has a passion for messing around with parsers and language implementations, recently released Koi – a pure Ruby implementation of a language parser, compiler, and virtual machine. If you’re ready to dive in at the deep end, the code for Koi makes for good reading.

Starting more simply, though, is Aaron’s latest blog post: A quick intro to writing a parser with Treetop. In the post, he covers building a “parsing expression grammar” (PEG) for a basic Lisp-like language from start to finish – from installing the gem, through to building up a desired set of results. It’s a great walkthrough and unless you’re already au fait with parsers, you’ll pick something up.

If thinking of “grammars” and Treetop is enough to make your ears itch, though, check out Aaron’s sister article: Writing an S-Expression parser in Ruby. On the surface, this sounds like the same thing as the other one, except that this is written in pure Ruby with no Treetop involvement. But while pure Ruby is always nice to see, it’s a stark reminder of how much a library like Treetop offers us.

If you’re interested in parsing merely as a road to creating your own programming language, though, check out Create Your Own Programming Language by Marc Andre Cournoyer. It’s a good read and even inspired CoffeeScript!

[ad] Check out Rails Cloud Hosting from Joyent. You can get started from a mere 83 cents per day and you get free bandwidth and persistent local storage with a 100% SLA.

How to Build a “Spy Camera” App for an Android Phone with Ruby and Sinatra

It’s been a great year for Ruby on Android, but no one knows it. You can start writing Ruby apps for Android devices TODAY. You don’t need to install any SDK, you don’t need to install some giant Eclipse IDE, and you certainly don’t need to write any Java.

Mike Leone

In Turn your Android Phone Into a Remote Spy Camera with Ruby in 15 Minutes, Mike Leone demonstrates how to use Ruby, Sinatra and Scripting Layer for Android (SL4A) to build and deploy a phone-hosted “spy camera” Web service.

SL4A is a system that allows you to run “scripting language” scripts and interactive interpreters on the Android platform. It currently supports JRuby, Python, Perl, Lua, JavaScript, BeanShell, and Tcl. Mike demonstrates how to set up a Sinatra project to use SL4A to run on an Android phone using JRuby. Upon receiving a request, Mike’s app takes a picture using the phone’s camera and serves it back over HTTP. He has also released the source code to a larger Ruby app called Broadcast that implements general Android device management functionality over HTTP.

Even if you don’t want to build a “spy camera”, Mike’s walkthrough is a must-read if building Web services in Ruby that can run directly on the Android platform is of interest to you.

A Walkthrough of Ruby In The Web Browser using IronRuby and Silverlight

With Microsoft’s IronRuby and Silverlight, Ruby can become a first-class citizen in the browser on Windows, Linux and OS X.. think <script type="text/ruby"> – yes, it’s possible! This walkthrough will get you started with using Ruby in the browser for HTML and vector-graphics-based applications. IronRuby enables Web developers to use Ruby to write client-side browser applications and even reuse code between the server and the client.

Background

IronRuby is a Ruby 1.8.6-compatible implementation, with ever-increasing support for 1.9 features that runs on Microsoft’s Common Language Infrastructure. The CLI blesses IronRuby with some powerful features like an efficient just-in-time compiler and sophisticated garbage collector. However, certain runtime-specific Ruby features are not supported on IronRuby, like continuations which interact with the runtime, certain performance-bogging parts of ObjectSpace, and the native Ruby C API. To support native-code interop we are planning on supporting FFI in the future (though today you can use the Win32API for Win32 calls, and the platform invoke APIs for the rest).

IronRuby runs on the .NET framework (2.0 SP1+) and Mono(2.0+), so IronRuby runs on a ton of platforms, including Mac OS and Linux. IronRuby also runs in the browser on Silverlight and Moonlight, a fairly-complete-but-tiny runtime which allows you to build “rich internet applications” … basically anything doing vector-graphics, webcam, audio, etc, in the browser.

Getting Started

Note: All code shown in this article can be found on GitHub.

To develop browser applications with IronRuby, you just need a Web server, text-editor, Web browser, and Silverlight installed for your browser to use:

1. Download and Install Silverlight for Mac or Windows

You’ll notice these installers are larger than advertised (7MB Windows, 13MB Mac): these are the “developer” versions since they contain error-message strings rather than just error codes, which is all the “consumer” versions have.

2. Set up any Web server, text-editor, and Web browser

I’ll be using the latest version of Firefox for the Web browser, the Apache Web server (which is part of Mac OS), and TextMate as the text-editor; on Windows you can use IIS (or any Web server of your choice) and any text-editor of your choice (notepad.exe is already installed, but I’d suggest E-TextEditor, InType, or even gVim for the more courageous). Silverlight officially supports IE, Firefox on Windows, and Firefox and Safari on Mac OS, but Opera and Google Chrome on both operating systems are known to work. See the system requirements page for more details.

3. Write Ruby in HTML pages

Here’s a simple “Hello, World”-style Ruby application in the browser:

1.png

Open the text-editor, place this code into it, and save the file to a convenient location where your Web server can access it; I’m saving mine to ~/Sites/ruby.html, since that will let me access it from http://localhost/~<username>/ruby.html (IIS users will have to put the file under C:\inetpub\wwwroot, which will let you access it from http://localhost/ruby.html) When you visit the site in a Web browser, you will see “Ruby says hello!”:

2.png

Note: if you just see “Loading …” for a very long time … did you already install Silverlight? There is no install detection in these examples. If you’re on a slow connection, make sure files aren’t still being downloaded (see below). And this will not run direct from the file system due to Silverlight’s security sandbox, so make sure you access it through a Web server.

Behind the scenes

That’s it! It’s very simple to get started with IronRuby in Silverlight, especially versus using ActionScript in Flash, or even the other languages like C# or VB.NET in Silverlight. Let me briefly explain what is going on behind the scenes to make IronRuby work so transparently with Silverlight.

The first script-tag runs dlr-<releasedate>.js which sets up a hidden Silverlight control on the page to download IronRuby and run any Ruby script-tags. The IronRuby binaries are downloaded to the browser cache, so they are not re-downloaded for any other application, unless the browser cache is cleared or is invalidated (Fig 2 and 3). These binaries set up the Silverlight control to process Ruby script-tags and execute them with IronRuby.

3.png

4.png

Note: IronRuby is not currently part of the Silverlight installation because keeping IronRuby open-source is a priority, and Silverlight is a closed-source project. The ability to download the binaries on the first load lets IronRuby stay as a separate project.

The specification for how all this works is in the Silverlight – Back to Just-Text paper; it is also a great source of documentation for the IronRuby-specific features, over and above what Silverlight already provides.

It’s worth pointing out that the entire application is just text; Silverlight IronRuby applications are made up of script-tags which have inline ruby code, or point to a ruby file on the Web server, along with other supported file-types referenced by script-tags to use vector graphics, archives of Ruby libraries (like the Ruby standard library, or a Gem), or even .NET assemblies.

Vector Graphics

A similar “Hello, World” example can be done with Silverlight’s vector-graphics as well:

5.png

6.png

The vector-graphics markup is called XAML, providing a simple XML-based markup language for defining any vector-graphics, like a user-interface. However, visual elements defined with XAML can also be defined through code; for example that <TextBlock> tag could have also been created from Ruby code, so you can decide to use XAML or just Ruby code to build vector-graphics:

t = TextBlock.new
t.name, t.text, t.font_size = "message", "Loading ...", 14

XAML is useful as there are great designer tools like Expression Blend which generate XAML that is directly consumable by Silverlight. However, if designers-tools aren’t your thing, the Magic library provides a very clean Ruby DSL for building user-interfaces.

In-Browser Ruby Console

A lot of Ruby development happens at an interactive Ruby command-prompt, and there is no exception with running Ruby in the browser. Turning on the Ruby command-prompt is simple; just enable the “console” setting for this page, and a Ruby command-prompt will appear at the bottom of the page, letting you run code against the active application:

7.png

8.png

document.message represents the DOM element with the id property of message (document.get_element_by_id("message") also works) and the click DOM event is hooked with the block, which changes the innerHTML of the clicked element. You can play around with code in this console window, and then when your satisfied move it into the actual HTML file.

Everything in Silverlight is usable through Ruby, just like it was originally written in Ruby. The is possible because IronRuby is directly integrated with the CLR. For example, you can see what methods are on the first DOM object in the HTML body by using normal Ruby idioms. For more information on what APIs are available in Silverlight, see the Full Silverlight 3 Documentation.

2D Drawing

A good way to get acquainted with new technology is to focus on an area and have some fun; here I’ll be using the 2D drawing libraries in Silverlight to make some “art”. The first example is ruby-squares.html, which draws 200 randomly size and randomly colored squares.

9.png

10.png

However, that’s not all the Ruby code running in the app; in the HTML file you’ll notice four script-tags before the code shown above. These files provide various helpers for working with Silverlight from Ruby.

11.png

repl.rb provides a way of enabling the command window through code, along with controlling when it’s visible based on the query-string (ruby-square.html doesn’t show the console at all, ruby-square.html?console will open the IronRuby Console panel, and ruby-square.html?console=off show the console with all panels hidden).

wpf_ext.rb contains some helpers to make dealing with Silverlight’s graphics libraries nicer from Ruby. This is only a fraction of the functionality that wpf_ext.rb normally provides, as this file was truncated for the article.

sketch.rb sets up Silverlight for 2D drawing, calling those setup and draw methods described above at the appropriate times; largely influenced by ruby-processing.

bouncer.rb bounce any Silverlight object around a Silverlight canvas; I’ll use this directly in the drawings. To experiment with it, run $sketch.toggle_bounce from the command-window to begin bouncing all the objects on the screen around. You can also re-run $sketch.setup to add more objects:

Speaking of ruby-processing, ruby-circles.html is one of the ruby-processing examples which I showed running in a Windows desktop app at RubyConf 2009, but can also run on the Mac through Silverlight.

12.png

Flickr Photo Viewer

While 2D animations are a fun way of exploring Ruby in the browser, they don’t really capture what making a “real-world” client-side web application would be like, with more standard user-interactions like clicking links and typing into text boxes. A simple Flickr photo viewer should do the trick though; using Flickr’s Web service to search for images and displaying them on the page:

13.png

The first thing this application needs to do is react when the “search” button is pressed. Ruby blocks (as well as procs) are used to handle events from the HTML page:

14.png

The create_request method takes the text in the textbox and makes a Web request to the appropriate Flickr Web service URL. When the request is complete, the applications shows the images Flickr returned:

15.png

The show_images method parses the response from Flickr into Ruby objects, and then the application’s view render the photos with ERB:

16.png

view.rb – rendering HTML from ERB templates

17.png

images.erb – an ERB template which creates HTML for displaying Flickr images

The erb method uses the exact same ERB that is part of the Ruby standard library, and what Rails uses by default in views. The ability to run the same libraries, such as ERB, or even your own application code, on both the client and the server is unique way of being “DRY”. It can help to blur the line between your client and server code, since everything can be written in Ruby, and open up new ways of sharing code and being productive.

Learn More

I hope this article has inspired you to look at using IronRuby for your next project, be it in the browser or not. Here are more resources to get you going with IronRuby in the browser:

jimmy.thinking – My blog has a bunch of tutorials on some interesting things that can be done with Silverlight and IronRuby, including Testing with Ruby and Embedding IronRuby in existing applications (though that article is for a native windows application, the same principles apply to the browser). Also, if you just want an update of IronRuby in general, my latest blog entry about the project’s status from RubyConf 2009 has all the latest information, as well as the other posts in that series.

Documentation PDF – Paper about how the IronRuby in Silverlight integration works.

ironruby.com/browser – Placeholder website for IronRuby in the browser; it currently has a redistributable download and some simple samples. Content from Gestalt’s website is currently under transition to this site, but the samples on that site are still relevant, as well as the newly released Gestalt Widget Pack, built on the latest version of IronRuby.

Full Silverlight 3 Documentation – Covers everything you can do with Silverlight 3. Examples are in C# or VB.NET, but are straight-forward to convert to Ruby.

github.com/ironruby/ironruby – IronRuby source code; Silverlight specific sources are all here. You can open bugs on the CodePlex project page.

And when in doubt, contact the IronRuby mailing list – you can also post online through ruby-forum.

EventMachine: Get Excited By Scalable Non-Blocking I/O

EventMachine is a simple(ish), fast, event-driven I/O library for Ruby. Its goal is to provide highly scalable I/O performance with an easy-to-use API wrapped around the nastiest parts of the process (since typical Ruby coding practices aren’t particularly event-driven friendly). Aman Gupta has put together an awesome 114-page deck of slides (also available as a PDF) that walks through EventMachine with lots of practical code examples.

The presentation walks through:

  • Who uses EventMachine (a lot of big guys – Heroku, GitHub, 37signals, Engine Yard, PostRank)
  • What EventMachine is good for
  • Ruby’s other I/O solutions (and why they suck)
  • What a “reactor” is
  • How to write asychronous code with EventMachine’s API
  • How EventMachine provides event-compatible iterators and timers
  • EventMachine’s message channels

Even though Aman’s slides are meant to go alongside a live presentation, they stand well on their own and provide more than enough incentive to check out EventMachine is event-driven I/O is something that would benefit you, so stop reading this post and get flicking through Aman’s awesome slides!

Building A Well Formed Number Handling Class From Scratch

Over on the Ruby Best Practices blog, somenums.pngRobert Klemme walks through the process of building a new numeric class from scratch in Ruby – taking into account all the gotchas and considerations that pop up along the way. Robert’s task is harder and more involved than you’d initially suspect.!

Robert chooses to build a HexNum class that can represent integers that are then displayed as hex numbers. There are considerations to be made with handling conversions from existing numeric types and his new HexNum class, conversions to other types, supporting standard comparison methods, and overloading.

All of the above concerns are covered in the post with all the quality and detail you should expect from the RBP blog by now. This post in particular should prove interesting to most Ruby developers who feel happy digging deep (no, this isn’t an article for beginners!).

[job] BeenVerified.com is currently looking for a Ruby and Rails developer to join their team in New York City. Alternatively, check out one of the other 12 jobs on our Ruby jobs board!

How Ruby Manages Memory and Garbage Collection

garbage.jpgGarbage Collection and the Ruby Heap is a presentation given by Joe Damato and Aman Gupta at the recent LA Ruby Conference. You only get the slides for now (all 70 of them!), but they’re very detailed and can almost work as a standalone concise e-book on Ruby’s garbage collection system.

Joe and Aman take a look at C memory management vs Ruby and show the difference between the stack and the heap. As a garbage collected language, Ruby takes the easy route by putting everything on the heap and the presentation demonstrates how the MRI (Matz’s Ruby 1.8) does this, as well as how objects are tracked within memory (right down to the underlying C structs).

cvsruby.png

MRI’s garbage collection scheme isn’t particularly well optimized (though Phusion’s Ruby Enterprise Edition has made some tweaks) and the presentation demonstrates the viability of some other garbage collection schemes (as always, the issue is compatibility with native extensions).

The presentation finishes off with a interesting walkthrough of using memprof (a Ruby memory profiler) to debug a memory leak in Rails 3.

[e-book] The Rails 3 Upgrade Handbook by Jeremy McAnally is a 120 page guide on migrating your apps from Rails 2.x to Rails 3.0. There’s a review of it on Rails Inside if you want to learn more.