Archive for the 'ruby' Category

Rails 2.0 to include Exceptional-style error handling

Sunday, September 30th, 2007

DHH posted today about the recently released preview release for rails 2.0. One notable piece of the update is introduction to a rescue_from directive that provides an easier interface to handling errors than rescue_action_in_public. If any of you have used Exceptional, you know this is very similar to what exceptional provides. Not surprisingly, both the core team and me drew our inspiration from John Wilger who as far as I can see came up with the original idea.

It’s cool to see that the core team made similar improvements to the idea that I did. That tells me that at least I wasn’t clueless in my designs for the plugin.

I guess this means exceptional will fade off into the sunset. I know it has been good to me, and will live on in past projects. I imagine that we at Satisfaction will replace it with the core code when we upgrade to 2.0.

link_to as a block helper

Tuesday, June 19th, 2007

When it comes to creating helpers for the view portion of satisfaction, I’ve started taking the approach that once I see something “ugly” twice in the rhtml that it should be extracted out into a helper. In many cases, before that.

Today’s wart? link_to calls that have html for the text content. take for example:

<%= link_to "<strong>#{product.name}</strong><span>#{pluralize(product.topic_count(company), 'topic')}</span>", href, :class => "product_label" %>

ewww… and that doesn’t even get into having href defined above in a <% %> block. So, I extended link_to with the help of alias_method_chain such that it will take a block argument instead of the its normal first parameter.

<% link_to browse_url(product), :class => "product_label" do %>
  <strong><%= product.name %></strong>
  <span>(<%= pluralize(product.topic_count(company), 'topic') %>)</span>
<% end %> 

Much more readable. See the code block_link_to.rb

15 minute hack: Poor man’s function composition

Thursday, June 14th, 2007

I loves me some functional programming and I loves me some Symbol#to_proc (which lets you do .each(&:upcase)).

One of those _fp_ features I wish I had in ruby-land was function composition. Specifically, I find myself writing things like:

initials = ["Foo". "Bar", "Baz"].map{|str| str.first.upcase}

That is fine, but just isn’t as cool as leveraging to_proc in some fashion. In the more “stupid, stupid, stupid” case, i’ve also seen things like:

initials = ["Foo". "Bar", "Baz"].map(&:first).map(&:upcase)  # Eww, unnecessary iterations...

Anways, Ruby does have function composition ([Proc#compose][2]), thanks to the Ruby facets project, but working directly with lambdas isn’t nearly as friendly as I desire. So, I spent 15 minutes to hack together a means that I like. Here’s what it looks like:

["foo", "bar", "baz"].map(&:first >> :upcase)

Which reads, map, using :first then :upcase. >> is left associative, like "foo".first.upcase, opposite of Haskell composition where foobar = foo . bar reads foo follows bar.

Also, the snippet linked below lets you do something like:

  class String
    compose(:initial, &:first >> :upcase)
  end
  "foo".initial   # => "F"

Now a re-implementation of ActiveSupport’s Module#delegate:

class Module
  def delegate(*methods)
    options = methods.pop
    unless options.is_a?(Hash) && to = options[:to]
      raise ArgumentError, "Delegation needs a target. Supply an options hash with a :to key as the last argument (e.g. delegate :hello, :to => :greeter)."
    end

    methods.each do |method|
      compose(method, &to >> method)
    end
  end
end

Perhaps not necessary, but I found it interesting and fun to write. Thoughts?

compose.rb

Erlectricity: Hi Ruby, I’m Erlang.

Tuesday, May 8th, 2007

update: this pre-release is up and running on rubyforge:

sudo gem install erlectricity

As I said in my previous article, I’m very stoked about working with Erlang. Usually most forays into new languages mean new projects and new explorations: Erlang has been no different. I usually end up in some middle ground where I try to improve the current language I’m working in with the new language: With C# -> Ruby it was a code generator written in Ruby that produced the cookie cutter DALs that I was plagued with, and this time around I immediately started to gravitate towards interoperation between erlang and ruby.

I’m not the only one with this idea (I’ve never claimed to be original), with several others working on using JSON to bridge the gap. That is all well and good, but considering how good erlang is at expressing itself across networks, I’d rather see something closer to the erlang-way. And that is why I set about creating what I call Erlectricity.

Before I go further, a code sample is in order. The following code is a passthrough daemon to Tinder, (the Campfire API gem) that lets you post to campfire from erlang. Even more before I show you the code, here is the google code site: http://code.google.com/p/erlectricity/, with the source being: http://erlectricity.googlecode.com/svn/trunk/. And now…

The Ruby:

require 'rubygems'
require 'erlectricity'
require 'tinder'

domain, email, password, roomname = *ARGV campfire = Tinder::Campfire.new domain campfire.login email, password room = campfire.findroombyname room_name

receive do match(:speak, string(:comment)) do room.speak comment receive_loop end

match(:paste, string(:comment)) do room.paste comment receive_loop end end

room.leave if room

And some erlang to call it (i’m omitting some code, please see the tinderl.erl example in the source to see the code that enables the calls below):
tinder:start("thedomain", "myemail@gmail.com", "mypassword", "theroom"),
tinder:speak("hey, hey kids!"),
tinder:paste("Im Krusty the Klown!").
At first, this was going to be a JRuby layer over JInterface, the Java -> Erlang bridge. That was all well and good, and worked fine, but it had a major flaw: It was tied to JRuby, leaving out the majority of Rubyists. JRuby is super exciting, and I was super stoked the first time I got ruby running inside a prototype game using The JMonkey Engine, but I didn’t want to be the person to exclude. I decided at this initial stage to use the Erlang port system, a means of starting and communicating with a separate process. As a consequence, I implemented most of the Erlang distribution format. Why re-invent the wheel when erlang has termtobinary and binarytoterm? Plus, it’s fun investigating the Erlang distribution format, even though only a subset is used for termtobinary.

As an aside, one reason to re-implement termtobinary and its sibling is because of the limited nature of Erlang’s type system.

You’ll also notice in the example directory ‘gruff’: 2 hours of hacking invested into rendering Gruff graphs through Erlectricity. Below is a graph generated using the stat_writer example to graph memory usage while running ab against webtool:

This was as a response to Yariv, and his desire for a graphing library in erlang like gruff. The example isn’t by any means a real solution, merely a demostration that this could be a viable solution.

The goal of Erlectricity is two-fold: expose ruby code to erlang, such that erlang applications can take advantage of the breadth of ruby libraries, and secondly, expose the OTP to ruby such that fault-tolerant distributed systems will be easier to develop. Neither of those goals are realized in Erlectricity’s current form, but it is a good base to work from towards those goals. Also, the two examples included demonstrate the former, and I’m playing around with something meaningful to demonstrate the latter.

This post is already about 3-times too long, but let me real quickly describe the structure of an erlectric app on the ruby side. The programming model follows the concurrency model of erlang, so read up on how erlang processes messages if you get confused. I’ll also describe it in further detail in an additional post. So, the core of an app using erlectricity is the receive loop, which looks like:

receive do
  match(:hello, string(:yourname)) do
    send! :helloreceived, “You stink, #{yourname}”
    receiveloop
  end
  match(:goodbye){ }
end
The receive block says “get a message, blocking if there are none on the wire”. When a message is received in this state it is compared with each of the match blocks in turn. The match block in the example says “If the message looks like the symbol :hello, and a string, bind the string object to the variable yourname and run the block.” Normally, when receiving a message, the code would then jump out of the receive block, but since the return value of the match block is receiveloop, the program tries to process another message against the same supplied match blocks. You’ll also notice that if the process receives a message that is just the symbol :goodbye, the app will simply fall out of the receive loop.

Here are some tips if you would like to play around with Erlectricity:

  1. Email me if you have any trouble: nullstyle@gmail.com
  2. Pass strings as binaries to ruby. “haha” will come out as [104, 97, 104, 97] in ruby, but <<”haha”>> will come out as “haha” in ruby. See my comment above about the limited type system in erlang. I’ll make a separate post about this issue, because I want to talk more fully about why I made this choice.
  3. Make sure your port is created with the {packet, 4} and binary options. Creating a port with {packet, 2} will have your ruby process never receiving any messages. Not having binary responses enabled will cause trouble when you try binarytoterm to get the response. This is an area for further improvement.
  4. Its a good idea to include catch-all clauses while you are working out the interaction issues. It greatly sped up my debugging time when I had the program yell at me when I sent an improper message
I would like to do several things with Erlectricity. first of all I would like to remove the possibility of programmer error in as many places as possible. There isn’t much work to do in this regard on the ruby-side(as far as I can tell, feedback is always welcome), but the hoops you need to jump through on the erlang side should go away. I’m thinking about abstracting away the framework bits and creating a behavior that you can implement in a callback module, similar to how the OTP does things. Putting a layer on the erlang side between user code and the port will allow me to smooth out some of the type translation issues too.

You can install erlectricity with:

sudo gem install erlectricity --source http://gems.nullstyle.com/
I’m in process of opening up the rubyforge project, so you’ll be able to drop the –source in a couple days. Stay tuned for more info, examples, and improvements as time marches forward.