Beware of the Proxy design pattern -read method_missing-

Ruby 1 Comment »

You probably read about how easy it was to implement the Proxy design pattern in Ruby.

Thanks to the Ruby method_missing method, you can pass messages to underlying objects. See the previous article Local resource available in the wild, thanks to DRb for a fully described example.

But there’s one caveat, you have to be very careful when implementing your method_missing method.

Take this code for example:

def method_missing(name, *args, &block)
  # Get the first arg, which contain information about which underlying
  # object to call.
  id = arg[0]
 
  # Call the corresponding underlying object with the first argument removed
  my_underlying_objects[id].__send__(name, *args[1..-1], &block)
end

If you execute this code, you’ll be stuck in an infinite loop. Why ? There’s a typo, one typo which will cause a segmentation fault. I wrote arg[0] instead of args[0].

To detect this problem before it happens, we can take advantage of the Kernel#caller method. It generates the current execution stask. Here is how we can use it to detect that the current object is calling himself:

def method_missing(name, *args, &block)
  # Check that we're not calling 'method_missing' recursively
  if caller.first.include?(__FILE__)
    raise "#{self.class} is calling itself -method #{name}-. Verify that you do not call a non existing method !!"
  end
 
  # Get the first arg, which contain information about which underlying
  # object to call.
  id = args[0]
 
  # Call the corresponding underlying object with the first argument removed
  my_underlying_objects[id].__send__(name, *args[1..-1], &block)
end

That’s all, we just check that the caller method is not in the current file. If your method_missing code become more and more complex, especially if it includes some meta-programming tricks, you’ll feel A LOT safer!

One last thing: Kernel#caller is not what we could call a non-expensive method, you should only use it in development.

Go faster to your Home directory in the Terminal

Mac 1 Comment »

In any Unix system, to go to your Home directory, you’d type this:

cd ~

The ~ character is hidden on Mac keyboards but like all other special characters, it is cleverly placed. You just have to push those keys: Option n.

Why cleverly placed ? Think about the spanish ñ character. Try all key combinations with the Option with and without the Shift key. You’ll be surprised. After several minutes, you’ll understand why each special character is placed on one specific character key.

But let’s get back to the subject of this post: to go to your Home directory, you don’t have to type the ~ character, just type:

cd

That’s it.

Now that you know everything about special characters, it’s time to learn the Mac OS X keyboard shortcuts. Feel free to visit the Mac Central website, your place for good, concise, Mac related hints.

Leopard, where are those Ruby gems?

Ruby 2 Comments »

It’s always useful to check the code of those downloaded Ruby gems. You should try for at least two reasons: learning and submitting bugs. It’s always a good idea to give technical details about bugs you encounter. The community is small and responsive, get involved :)

You’re lucky, Leopard user, Apple made a great work embedding Ruby in Mac OS X 10.5. You have the latest version of Ruby, 1.8.6, and RubyGems installed.

Apple guys set a specific directory for all Ruby related things.

/Library/Ruby/Gems/1.8/

This directory contains exploded gems and their documentation. For example, you can examine the content of the ActiveRecord gem and its documentation with those two commands (I hope you use TextMate…).

mate /Library/Ruby/Gems/1.8/gems/activerecord-2.1.0/
open /Library/Ruby/Gems/1.8/doc/activerecord-2.1.0/rdoc/index.html

No need to google “activerecord”, everything’s on you hard drive.

Note: Rubygems has evolved since the release of Leopard. But hopefully, it’s simple to update it. Just download the last version and one simple command will do the work.

Local resource available in the wild, thanks to DRb

Ruby 3 Comments »

You have a resource that you want to share between multiple processes, and it could be a resource persited on the local hard drive, like an index, a persitent hash (Berkeley DB, InfinitiyDB), or simply a file.

With DRb, aka Distributed Ruby, you can share a resource via TCP. DRb will do the annoying job for you: marshalling. And that is COOL, and RMI is NOT COOL.

As usual in Ruby, using a library is as simple as calling the require method. To use DRb in your application, write this:

require 'drb'

In this post, we’ll implement a Remote Hash. It will be accessible to an unlimited number of processes on an unlimited number of computers. Let’s code a simple DRb server for your resource.

class Server
  def start
    print "starting Ferret servers..."
    DRb.start_service("druby://localhost:7000", HashProxy.new)
    puts " done"
  end
 
  def join
    DRb.thread.join
  end
 
  def shutdown
    print "stopping Ferret servers..."
    DRb.stop_service
    puts " done"
  end
end
 
s = Server.new
s.start
trap("INT") {s.shutdown} # Catch CTRL-C to do a clean shutdown of the DRb server
s.join

The instance of HashProxy will be the distributed object between the DRb server and the DRb clients. We call it “proxy” because it will exactly have the same behaviour as the real resource hidden behind it. This is where the method_missing magic happen.

class HashProxy
  def initialize *args
    @local_resource = Hash.new *args
  end
 
  def method_missing(name, *args, &block)
    @local_resource.__send__(name, *args, &block)
  end
end

The Object.__send__ method is an alias to Object.send, to avoid conflics with a possibly existing method named send in the current object or its superclasses or included modules.

There is one problem with this implementation, DRb will, like a web server, handle client requests simultaneously. We have to protect our hash thanks to a mutex. Every clients will have to wait in line to access the remote resource.

require 'thread'
 
class HashProxy
  def initialize *args
    @mutex = Mutex.new
    @local_resource = Hash.new *args
  end
 
  def method_missing(name, *args, &block)
    @mutex.synchronize do
      @local_resource.__send__(name, *args, &block)
    end
  end
end

As we said earlier, each method of HashProxy, and so each method of Hash, is now available to any remote Ruby code, using the HashProxy class, instead of Hash:

class RemoteHash
  def initialize
    @hash_proxy = DRbObject.new(nil,"druby://localhost:7000")
  end
 
  def method_missing(name, *args, &block)
    @hash_proxy.__send__(name, *args, &block)
  end
end

In your application, you’ll use your remote resource like a local resource, without knowing about those network and marshalling things.

h = RemoteHash.new
h[:roger] = 1
h[:moore] = -1
p h[:roger] # => 1

Unfortunately, I couldn’t call methods with blocks.

h.select {|k,v| v > 0}
# =>
# ArgumentError: wrong number of arguments (0 for 1)
# 
# method select at line 9
# method __send__ at line 9
# method method_missing at line 9
# at top level  at line 17
# Program exited.
 
p h.sort {|a,b| a[1]<=>b[1]}
# =>
# DRb::DRbConnError: DRb::DRbServerNotFound
# 
# method current_server in drb.rb at line 1650
# method to_id  in drb.rb at line 1712
# method initialize in drb.rb at line 1048
# method new  in drb.rb at line 642
# method make_proxy in drb.rb at line 642
# method dump in drb.rb at line 559
# method send_request in drb.rb at line 605
# method send_request in drb.rb at line 906
# method send_message in drb.rb at line 1194
# method method_missing in drb.rb at line 1086
# method open in drb.rb at line 1170
# method method_missing in drb.rb at line 1085
# method with_friend  in drb.rb at line 1103
# method method_missing in drb.rb at line 1084
# method __send__ at line 9
# method method_missing at line 9
# at top level  at line 18
# Program exited.

One last word, about method_missing, Jay Field wrote an excellent article about dynamically defining the methods of an external class, instead of using method_missing. It will surely help you debugging your piece of art.

Install Apache Tomcat 5.5.x on Mac OS X Tiger or Leopard

Java 6 Comments »

I was working at La Cantine today, a great co-working place in Paris. In fact, I prefer this place than incubators. It’s like a big loft with long tables, cozy armchairs, sofas, a bar; anything you need to work in an productive environmnent. You’ll meet developers, designers, investors, technical book writers, etc.

And when you work/play/chat/drink in a co-working place, there’s regularly someone with a problem. Noob questions like “I can’t connect to the Wifi network”! “I can’t restore my backup!”, and also more advanced questions.

So, I was asked today: “How can I install Tomcat on my MacBook ?”. I supposed that in 2008, there should be tons of articles about installing Tomcat on a Mac, but I did not find one. Actually, I admit that I only looked at the first result page on Google… you know that Google is pretty good at crawling blogs. Did you try to search for flex ruby graph or ruby sqs graph ?

Before calling for help, the guy -let’s call him Roger- read some forum posts, began to install Tomcat in /usr/local, set its environment variables, and ran into the famous error message “The BASEDIR environment variable is not defined correctly”.

Roger, you need to know one thing: there’s develoment environment and production environment. So do those three simple things and you’ll be fine:

  • Untar Tomcat to your /Applications directory. Important: Take the tar.gz archive, it keeps file modes and authorizations for *nix systems
  • .

  • With the Terminal, create a file named .bash_profile in your home directory (aka ~) via the command nano ~/.bash_profile and copy-paste this text:
export CATALINA_HOME=/Applications/apache-tomcat-5.5.26
export JAVA_HOME=/System/Library/Frameworks/JavaVM.framework/Versions/1.5/Home
alias starttomcat="$CATALINA_HOME/bin/startup.sh"
alias stoptomcat="$CATALINA_HOME/bin/shutdown.sh"
  • Start a new Terminal and type starttomcat and stoptomcat to… you guess.

I did put Tomcat in the /Applications folder for on reason: it’s not hidden in the Finder and it’s easily accessible. Noobs do not understand the difference between system directories and friendly directories on Mac OS X. And they want to see the Tomcat folder, so they can put their .war files in the webapps directory and check log files with one click on the mouse button.

By the way, I didn’t ask Roger why the hell he was coding a new project in Java. And I really do not want to know…

Dynamic Graph Visualization in Flex, Ruby and Amazon SQS - Part 2 - Ruby and SQS

Ruby 1 Comment »

Update: An Amazon guy sent me a mail because I used the old SQS API. Please use the gems from RightScale instead of the one presented below, it supports the new SQS WSDL, which is cheaper.

Thanks to the first part of this article, you master Flex and ActionScript 3 like nobody. Don’t you ?

It’s now time to retrieve some data. You could need a realtime updated graph to monitor a bunch of rackmount servers, your database, your mailbox, or the activity of your friends of Facebook, who knows. After taking a look at the Technorati top blogs list, I wondered what was the activity of readers on those blogs, ie. check how many comments are posted on their last articles.

This article will focus on the data provider, coded in Ruby. And remember, the retrieved data will be sent to an Amazon SQS queue.

I know, why would we need to use Ruby and Amazon SQS when we can do all those tasks directly in ActionScript 3 ? Like I wrote before, you could use it to monitor something which is not directly accessible by Flash, as the ActionScript code is executed on the client computer. Data providers could also be CPU/Network expensive and/or spreaded in a computing cloud. Hey, finally, don’t you want to read some Ruby code ?

Let’s parse those RSS feeds. You’ll need one gem, the “Flexible RSS and Atom reader for Ruby”: simple-rss.

require 'open-uri' # To retrieve data from the word wide web
 
require 'rubygems' # Needed to load installed gems
require 'simple-rss'
 
feeds_url = %w{
  http://feeds.feedburner.com/Techcrunch
  http://feeds.feedburner.com/Mashable
  ... a lot more here ...
}
 
feeds_url.each do |feed_url|
 
  # Parse each feed
  rss = SimpleRSS.parse open(feed_url)
  rss.entries.each do |entry|
 
    begin
      entry.guid << "/" unless entry.guid[-1] == 47
      comments_feed_url = "#{entry.guid}feed"
      rss_comments = SimpleRSS.parse open(comments_feed_url)
      rss_comments.entries.each do |comment|
        puts "Found a new comment #{comment.title} on '#{entry.title}'"
      end
    rescue
      puts "There was a problem retrieving comments from #{comments_feed_url}"
    end
 
  end
end

As I want to keep the code simple, I only chose Wordpress blogs, as you can retrieve the comments feed for each entry easily: adding “/feed” to the end of the entry url.

Whis this code, you’ll get something like:

Found a new comment By: Tim-TechFruit on 'LoveFilm merges with Amazon’s DVD rentals'
Found a new comment By: Esi on 'Cuill has Irish roots'
Found a new comment By: Sam B on 'Women more likely to give passwords for chocolate? Yeah, but did they offer the men guilt-free sex?'
Found a new comment By: john b on 'Women more likely to give passwords for chocolate? Yeah, but did they offer the men guilt-free sex?'
Found a new comment By: Carl on 'Women more likely to give passwords for chocolate? Yeah, but did they offer the men guilt-free sex?'

We said earlier that we wanted to monitor the comments, right ? We will put this code in a infinite loop, and keep the found comments in a hash, just to announce only the new ones.

comments = {} # hash of found comments
 
loop do
  feeds_url.each do |feed_url|
 
    # Parse each feed
    rss = SimpleRSS.parse open(feed_url)
    rss.entries.each do |entry|
 
      begin
        entry.guid << "/" unless entry.guid[-1] == 47
        comments_feed_url = "#{entry.guid}feed"
        rss_comments = SimpleRSS.parse open(comments_feed_url)
        rss_comments.entries.each do |comment|
          if not comments[comment.guid]
            comments[comment.guid] = comment.guid
            puts "Found a new comment #{comment.title} on '#{entry.title}'"
          end
        end
      rescue
        puts "There was a problem retrieving comments from #{comments_feed_url}"
      end
 
    end
  end
 
  puts "... waiting 1 minute ..."
  sleep 60
end

Whis this code, you’ll get something like:

Found a new comment by: Buster Cherry on 'Crazy Gets Evicted!'
Found a new comment by: DONT MAKE FUN OF HOMELESS on 'Crazy Gets Evicted!'
Found a new comment by: joe on 'Crazy Gets Evicted!'
Found a new comment by: Oh, Give Me a Home Where the... on 'Crazy Gets Evicted!'
... waiting 1 minute ...
... waiting 1 minute ...
... waiting 1 minute ...
Found a new comment by: beth on 'Ben Savage Is Still Alive'
Found a new comment by: Dain Starr on 'Ben Savage Is Still Alive'
Found a new comment by: I LOVE BEN SAVAGE!! on 'Ben Savage Is Still Alive'
Found a new comment by: Chuy on 'Ben Savage Is Still Alive'

It would be a good idea to check each new feed in a new thread, as 99% of the processing time is devoted to network requests. We’ll use a new gem for this: fastthread.

require 'fastthread'
 
threads = []
comments = {} # hash of found comments
 
feeds_url.each do |feed_url|
  t = Thread.new do
  loop do
      rss = SimpleRSS.parse open(feed_url)
      rss.entries.each do |entry|
 
        # ...
      end
 
      sleep 60
    end
  end
  threads << t
 
end
 
# Wait for all threads to exit (never, in this case)
threads.each { |t| t.join }

With this code, you’ll see the same output as earlier, but, you guess, with every messages mixed.

Finally, we can put our data in an Amazon SQS queue. In the graph, we’ll show one node per feed, add a child node when a new comment comes in. This way, we only need one message format, only containing the feed URL.

It’s time to register to Amazon SQS. You’ll get two keys: AWS access key and AWS secret access key. You’ll also need to install a new gem: SQS.

Just require ’sqs’ as the other gems, set your credentials, and create a queue named “feeds”.

require 'rubygems'
require 'sqs'
 
SQS.access_key_id = "my key here"
SQS.secret_access_key = "my secret key here"
queue = SQS.create_queue "feeds"

Each time a comment is detected, we can put a message in the queue.

rss_comments.entries.each do |comment|
  if not comments[comment.guid]
    comments[comment.guid] = comment.guid
    puts "Found a new comment #{comment.title} on '#{entry.title}'"
    queue.send_message "#{feed_url}"
  end
end

You can download the full code here.

When you’ve finished playing, you can delete the queue with the following piece of code.

SQS.get_queue("feeds").delete!

You’re now ready to animate this with our Flex graph. It will be the subject of the next and last part of this article. (actually, there will be a fourth post to illustrate all of this, think about a racing game…).

Dynamic Graph Visualization in Flex, Ruby and Amazon SQS - Part 1 - Flex

Ruby 10 Comments »

In this first post, we’ll try to create a animated graph in Flex. Data is retrieved periodically from an Amazon SQS queue and the graph is updated in realtime. Why Amazon SQS ? You work in a distributed environment, don’t you ?

As Ruby is my favourite language these days, the data provider will be implemented in Ruby. Is there a better language to show concise but featureful snippets of code ?

Part 1 is dedicated to Flex. I’m not a real fan of Flash for web apps, but sometimes, you can’t avoid it when you have to impress colleagues… I’m sure you could do the same thing with Silverlight, but as far as I know, my Mac Mini does not really like Microsoft IDEs. In the second part, we’ll retrieve data from a famous API, in Ruby, and put them in an Amazon SQS queue. The last and third part will show you how to interact between Flex and Amazon SQS, the graph will be alive, to make you glad like hell.

You’ll need the Flex 3.0 SDK. For Flex and Air fans out there, you can obviously use Flex Builder 3 Professional.

If you discover the Flex 3.0 SDK, take a look at the Adobe Flex resources website, a gold mine. If you fell lazy, for now, simply follow these instructions to install the Flex SDK.

It’s time to begin coding, simply create a .mxml file. It will contain all our Flex code.

<?xml version="1.0"?> 
<mx:Application
    xmlns:mx="http://www.adobe.com/2006/mxml"
    xmlns:adobe="http://www.adobe.com/2006/fc">
</mx:Application>

You can compile and run it with the commands:

mxmlc dynamicgraph.mxml
open dynamicgraph.swf

See this code in action.

To generate graphs, I noticed two Flex components, flexvizgraphlib and SpringGraph. flexvizgraphlib seems promising but misses one mandatory feature for this project: realtime node updates. SpringGraph is a bit old, but it’s well designed and answers our need, so let’s use it. Copy the SpringGraph.swc file to the “/frameworks/libs” folder of your Flex SDK installation, simple.

Let’s create a simple graph:

<?xml version="1.0"?> 
  <mx:Application
      xmlns:mx="http://www.adobe.com/2006/mxml"
      xmlns:adobe="http://www.adobe.com/2006/fc"
      initialize="onLoad()">
 
  <adobe:SpringGraph id="springgraph" width="100%" height="100%" 
  	backgroundColor="#869ca7" repulsionFactor="1">
    <adobe:itemRenderer>
      <mx:Component>
          <mx:Label fontSize="14" text="{data.id}" color="#ffffff"/>					
       </mx:Component>
    </adobe:itemRenderer>
  </adobe:SpringGraph>
 
  <mx:Script>
    <![CDATA[
      import com.adobe.flex.extras.controls.springgraph.Graph;
      import com.adobe.flex.extras.controls.springgraph.Item;
 
      private var graph: Graph = new Graph();
      private var rootItem: Item;
 
      private function onLoad(): void {
        addNode("R");
        addNode("1", "R");
        addNode("1.1", "1");
        addNode("1.2", "1");
        addNode("1.3", "1");
        addNode("2", "R");
        addNode("2.1", "2");
        addNode("2.2", "2");
      }
 
      private function addNode(id:String, linkedTo:String = null): void {
        var item: Item = new Item(id);
        graph.add(item);
        if(linkedTo)
          graph.link(graph.find(linkedTo), item);
        springgraph.dataProvider = graph;
      }
    ]]>
  </mx:Script>
 
</mx:Application>

See this code in action.

It seems to be a lot of code, but it’s dead simple. You’re smart, just read it and you’ll understand it.

So, we’ve just created an animated 8-nodes graph, and we can even drag nodes and pan the whole graph with the mouse. Remember, the objective of this project is to retrieve data from an Amazon SQS queue. We want this to be fluid, so we won’t update the graph more than x times per second. Let’s implement a Timer which will periodically add nodes to our graph.

import com.adobe.flex.extras.controls.springgraph.Graph;
import com.adobe.flex.extras.controls.springgraph.Item;
import flash.utils.Timer;
import flash.events.TimerEvent;
 
private var graph: Graph = new Graph();
private var rootItem: Item;
private var timer: Timer = new Timer(300, 0);
private var itemCount: int = 0;
 
private function onLoad(): void {
  addNode("R")
  timer.addEventListener("timer", timerHandler);
  timer.start();
}
 
public function timerHandler(event:TimerEvent):void {
  addNode(new Number(++itemCount).toString(), "R");
 
  if(itemCount == 30)
    timer.stop();
}
 
private function addNode(id:String, linkedTo:String = null): void {
   (...)
}

See this code in action.

This code creates 30 nodes, every 300 milliseconds. And to reward your hard work, you can still play with the nodes while the graph is updated. We can now put the finishing touches, special effects. Let’s blur new nodes and play a funny sound as they appear.

Add this XML code after the <adobe:SpringGraph/> tag definition:

  <mx:Parallel id="newItemEffect">
    <mx:SoundEffect source="@Embed(source='assets/bloop.mp3')"/>
    <mx:Blur duration="200" 
      blurXFrom="10.0" blurXTo="0.0" 
      blurYFrom="10.0" blurYTo="0.0"/>
  </mx:Parallel>

You can then simply associate this effect to “new-node” events:

private function onLoad(): void {
  addNode("R")
  timer.addEventListener("timer", timerHandler);
  timer.start();
  springgraph.addItemEffect = newItemEffect;
}

See this code in action.

Of course, all credits go to Mark Shepherd, for providing this wonderful library and its source code.

If you want to know more about Flex, especially making a Rails app powered by a Flex UI, go buy Flexible Rails: Flex 3 on Rails 2 ! French readers, you can get it here. I bought this book 2 years ago, when it still was a beta PDF. Peter Armstrong then found a paperback editor, and you’ll easily understand why if you read it.

Check back soon for the next part.

WP Theme & Icons by N.Design Studio
Entries RSS Log in