<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	>

<channel>
	<title>nutrun &#187; Software</title>
	<atom:link href="http://nutrun.com/weblog/category/software/feed/" rel="self" type="application/rss+xml" />
	<link>http://nutrun.com</link>
	<description>Just another WordPress weblog</description>
	<pubDate>Sat, 10 May 2008 15:10:14 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.5</generator>
	<language>en</language>
			<item>
		<title>Confidence as a test code metric</title>
		<link>http://nutrun.com/weblog/confidence-as-a-test-code-metric/</link>
		<comments>http://nutrun.com/weblog/confidence-as-a-test-code-metric/#comments</comments>
		<pubDate>Sat, 10 May 2008 15:10:14 +0000</pubDate>
		<dc:creator>George Malamidis</dc:creator>
		
		<category><![CDATA[Software]]></category>

		<guid isPermaLink="false">http://nutrun.com/?p=139</guid>
		<description><![CDATA[With testing occupying a major part of our development process, we have often attempted to quantify test code quality. Like many things, it is worth considering how test code ultimately manifests itself in terms of added value. This is why Stuart and I recently tend to conclude that, stripped from technically granular details, test code [...]]]></description>
			<content:encoded><![CDATA[<p>With testing occupying a major part of our development process, we have often attempted to quantify test code quality. Like many things, it is worth considering how test code ultimately manifests itself in terms of added value. This is why <a href="http://no-new-ideas.blogspot.com/" title="No New Ideas">Stuart</a> and I recently tend to conclude that, stripped from technically granular details, test code must fundamentally contribute in building confidence that the system under test is complete, a proof that what we&#8217;ve built is and will continue working as intended.</p>
<p>A working system fulfilling its business objectives can be considered complete enough, but, if not easily extensible and maintainable, will not grant itself to the conclusion of being as good as it can be. Advancements in software development methodologies that assist in delivering working software that is easy to extend and maintain - higher level abstractions, modeling and design - have been driven by the need to reduce technical debt. Technical debt can be viewed as the cost of change.</p>
<p>Test code is code, too. As code bases grow more elaborate, test code also suffers from technical debt, demanding methods to eliminate the factors that hinder its maintainability and extensibility. Present procedures geared towards extensible and maintainable test code are habitually counter-proportional to the amount of confidence they achieve.</p>
<p class="centered"><img class="boxed" src="http://farm4.static.flickr.com/3143/2479820537_9f597a7c42.jpg" alt="The confidence scale"/></p>
<p>The different categories on the scale are not mutually exclusive, in fact they are commonly combined as members of a suite that exercises the system in various degrees of instrumentation. Walking the scale from left (empty) to right (full), we move from tests that are generally easier to write, understand, run and maintain but at the same time are less representative of the <em>real</em> system with all its components integrated.</p>
<p>Dependency neutral tests with all of the tested component&#8217;s dependencies stubbed are disconnected, vaguely describe how the component interacts with its environment and offer minimal proof that the component will work as specified once a member of the application ecosystem.</p>
<p>The fundamental difference between interaction based dependency neutral tests and their stubbed counterparts is the accurate interaction specification of collaborating components through the use of mock objects instead of stubs. Here, we concentrate on specifying the contract of communication between two components. Although much closer to how the actual system operates, these tests are still disconnected. Despite the accurate specification of the interaction, we have don&#8217;t have complete proof that the pieces fit. In particular, interaction based dependency neutral tests do not offer proof that the mocked collaborators have been tested to work.</p>
<p>It becomes apparent that the major flaw of interaction based dependency neutral tests is their disconnect from their peers.</p>
<p>As we move towards the &#8220;full&#8221; side of the confidence scale, tests tend to become larger and more complicated. Wired tests draw a picture much closer to that of the system in its entire form but suffer from poor defect localization (test failures are not always directly related to the intent of the specific test) and disrespect encapsulation (setup code often exposes the behavior of components irrelevant to the context of the current test). The dependency wired tests&#8217; contribution to technical debt is much more significant.</p>
<p>Understanding the importance of confidence in our system and aiming to reduce technical debt, <a href="http://synthesis.rubyforge.org/" title="synthesis">Synthesized Testing</a> suggests a solution that attempts to rectify the disconnect of lightweight, interaction based dependency neutral tests and reduce the need of overarching, prone to technical debt dependency wired tests.</p>
]]></content:encoded>
			<wfw:commentRss>http://nutrun.com/weblog/confidence-as-a-test-code-metric/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Unambiguous command abbreviation</title>
		<link>http://nutrun.com/weblog/unambiguous-command-abbreviation/</link>
		<comments>http://nutrun.com/weblog/unambiguous-command-abbreviation/#comments</comments>
		<pubDate>Wed, 07 May 2008 21:36:38 +0000</pubDate>
		<dc:creator>George Malamidis</dc:creator>
		
		<category><![CDATA[Software]]></category>

		<guid isPermaLink="false">http://nutrun.com/?p=138</guid>
		<description><![CDATA[When using RubyGems from the command line, I almost always type sudo gem i synthesis as opposed to sudo gem install rails, the emphasis targeted at using &#8220;i&#8221; instead of &#8220;install&#8221;, of course. The gem executable happily understands what command it is being asked to execute when provided with the first few letters of the [...]]]></description>
			<content:encoded><![CDATA[<p>When using <a href="http://www.rubygems.org/" title="RubyGems Manuals">RubyGems</a> from the command line, I almost always type <code>sudo gem i synthesis</code> as opposed to <code>sudo gem install rails</code>, the emphasis targeted at using <em>&#8220;i&#8221;</em> instead of <em>&#8220;install&#8221;</em>, of course. The <code>gem</code> executable happily understands what command it is being asked to execute when provided with the first few letters of the command, as long as those letters are not ambiguous, i.e. don&#8217;t clash with the names of other commands. So even though <code>sudo gem u foo</code> complains that <code>Ambiguous command u matches [uninstall, unpack, update]</code>, <code>sudo gem uni foo</code> will uninstall the specified gem.</p>
<p>Here&#8217;s how this is implemented in RubyGems.</p>
<pre>
def find_command(cmd_name)
  possibilities = find_command_possibilities(cmd_name)
  if possibilities.size &gt; 1
    raise "Ambiguous command #{cmd_name} matches [#{possibilities.join(', ')}]"
  end
  if possibilities.size &lt; 1
    raise "Unknown command #{cmd_name}"
  end

  self[possibilities.first]
end

def find_command_possibilities(cmd_name)
  len = cmd_name.length
  self.command_names.select { |n| cmd_name == n[0,len] }
end
</pre>
<p>In the same vein, although not strictly a command abbreviation, <a href="http://www.dtsato.com/blog" title="Danilo Sato">Danilo</a> pointed out <a href="http://git.or.cz/" title="Git - Fast Version Control System">git</a> understands abbreviated revision hashes, so it&#8217;s possible to use something like <code>git diff d0a..HEAD</code> even with the hash&#8217;s complete representation being <code>d0aa7dd4aa9a95090df1e0b9d0f426d5a5bd56ae</code>.</p>
<p>Less typing is almost always a good option to have. The easy to implement <em>Unambiguous command abbreviation</em> trick adds a subtle usability improvement to command line interfaces and holds a nice treat to the utility&#8217;s power users.</p>
]]></content:encoded>
			<wfw:commentRss>http://nutrun.com/weblog/unambiguous-command-abbreviation/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Distributed programming with Jabber and EventMachine</title>
		<link>http://nutrun.com/weblog/distributed-programming-with-jabber-and-eventmachine/</link>
		<comments>http://nutrun.com/weblog/distributed-programming-with-jabber-and-eventmachine/#comments</comments>
		<pubDate>Sun, 04 May 2008 20:38:04 +0000</pubDate>
		<dc:creator>George Malamidis</dc:creator>
		
		<category><![CDATA[Software]]></category>

		<guid isPermaLink="false">http://nutrun.com/?p=137</guid>
		<description><![CDATA[Jabber and its underlying protocol XMPP are typically associated with instant messaging applications, although the breadth and flexibility of the technology allows for implementations that can span further from traditional online chatting.
ejabberd is a fault tolerant and clusterable Jabber/XMPP server written in Erlang and presents an interesting option as a simple, lightweight and scalable message [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.jabber.org/" title="Jabber.org | open instant messaging and presence">Jabber</a> and its underlying protocol <a href="http://www.xmpp.org/" title="XMPP Standards Foundation">XMPP</a> are typically associated with instant messaging applications, although the breadth and flexibility of the technology allows for implementations that can span further from traditional online chatting.</p>
<p><a href="http://www.ejabberd.im/" title="ejabberd Community Site | the Erlang Jabber/XMPP daemon">ejabberd</a> is a fault tolerant and clusterable Jabber/XMPP server written in <a href="http://www.erlang.org/" title="Erlang">Erlang</a> and presents an interesting option as a simple, lightweight and scalable message transport for distributed applications.</p>
<p><a href="http://rubyforge.org/projects/eventmachine/" title="RubyForge: Ruby/EventMachine: Project Info">EventMachine</a> is a simple and fast library for lightweight concurrency in Ruby. Its use mainly involves, but is not limited to, spawning lightweight processes whose execution can be programatically scheduled, easy and fast socket abstractions and an implementation of the Deferrable pattern as introduced by the <a href="http://twistedmatrix.com/trac/" title="Twisted">Twisted</a> event-driven Python networking engine.</p>
<p>When a Ruby class includes the  <code>EventMachine::Deferrable</code> module, it is provided with the ability to accept arbitrary callbacks and errbacks that will get executed when its deferred status changes, in particular when it is set to either <code>:succeeded</code> or <code>:failed</code>. Let&#8217;s look at a deferrable <code>Worker</code> class which performs a potentially long running operation.</p>
<pre>
class Worker
  include EM::Deferrable

  def heavy_lifting
    30.times do |i|
      puts "Lifted #{i}"
      sleep 0.1
    end
    set_deferred_status :succeeded
  end
end
</pre>
<p>Inside an EventMachine loop, we can add callbacks to a <code>Worker</code> instance and dispatch the expensive operation to a separate thread, or an evented process. The program&#8217;s execution will continue, with any callbacks attached to <code>Worker</code> executed once its deferred status is set.</p>
<pre>
EM.run do
  worker = Worker.new
  worker.callback {p "done!"}
  Thread.new {worker.heavy_lifting; EM.stop}
  puts "resuming remaining program operations"
end
</pre>
<p>Now, let&#8217;s look at combining <code>Worker</code> with Jabber to trigger long running jobs. For Jabber server duties, I am using ejabberd on an old laptop running Debian, but there&#8217;s no reason why a mass online Jabber service like <a href="http://www.google.com/talk/" title="Google Talk">Google Talk</a> could not be used for playing around with the example. Also, I&#8217;m using the <a href="http://xmpp4r-simple.rubyforge.org/" title="Jabber::Simple">xmpp4r-simple</a> Ruby library, which is a wrapper around <a href="http://home.gna.org/xmpp4r/" title="XMPP4R: XMPP/Jabber Library for Ruby">xmpp4r</a>.</p>
<pre>
jabber = Jabber::Simple.new("bot@thrash", "password")
at_exit{jabber.status(:away, "jabot down")}

EM.run do
  EM::PeriodicTimer.new(1) do
    jabber.received_messages do |message|
      case message.body
      when "exit" : EM.stop
      when "lift" :
        EM.spawn do
          worker = Worker.new
          worker.callback {jabber.deliver(message.from, "Done lifting")}
          worker.heavy_lifting
        end.notify
        jabber.deliver(message.from, "Scheduled heavy job...")
      else jabber.deliver(message.from, "Dunno how to #{message.body}")
      end
    end
  end
end
</pre>
<p>Inside an EventMachine loop, we check for new messages every second. The program understands two commands, <code>exit</code> and <code>lift</code>. The first quits the EventMachine loop and ultimately terminates the program&#8217;s execution. When <code>lift</code> is received, we instantiate a new <code>Worker</code> inside a spawned process and add a callback so that the <code>Worker</code> will notify the command issuer when the job has completed. Worth noting is the use of <code>notify</code> to schedule the spawned process. <code>notify</code> returns immediately making work dispatch non-blocking - upon issuing a <code>lift</code> command twice, a &#8220;Scheduled heavy job&#8230;&#8221; message will be sent to the job issuer twice before the first job completes.</p>
<p>I use <a href="http://www.adiumx.com/" title="Adium - Download">Adium</a> to send commands to the program - an interesting way of remote controlling or interacting with applications. Of course, the real interest lies in using the setup under discussion for inter-app communication. With multicast options, presence discovery, node status updates and more, there is lot to explore in terms of distributed application development, if <em>simple</em> and <em>lightweight</em> are two keywords to be found on the highest ranks of your list.</p>
]]></content:encoded>
			<wfw:commentRss>http://nutrun.com/weblog/distributed-programming-with-jabber-and-eventmachine/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Ruby mock instance</title>
		<link>http://nutrun.com/weblog/ruby-mock-instance/</link>
		<comments>http://nutrun.com/weblog/ruby-mock-instance/#comments</comments>
		<pubDate>Tue, 29 Apr 2008 14:11:32 +0000</pubDate>
		<dc:creator>George Malamidis</dc:creator>
		
		<category><![CDATA[Software]]></category>

		<guid isPermaLink="false">http://nutrun.com/?p=136</guid>
		<description><![CDATA[The common pattern for mocking class instances in Ruby involves setting an expectation on the new method of the class to return an object of the specified type. Consider the following User and Account classes.

class User
  attr_reader :name, :email

  def initialize(name, email)
    @name, @email = name, email
  end

  [...]]]></description>
			<content:encoded><![CDATA[<p>The common pattern for mocking class instances in Ruby involves setting an expectation on the <code>new</code> method of the class to return an object of the specified type. Consider the following <code>User</code> and <code>Account</code> classes.</p>
<pre>
class User
  attr_reader :name, :email

  def initialize(name, email)
    @name, @email = name, email
  end

  def contact
    send_email(@email)
  end
end

class Account
  def self.create(name, email)
    user = User.new(name, email)
    user.contact
  end
end
</pre>
<p>The test for the <code>Account#create</code> method would look like this:</p>
<pre>
require "rubygems"
require "mocha"
require "test/unit"

class AccountTest &lt; Test::Unit::TestCase
  def test_emails_user_on_account_creation
    user = User.new("", "")
    user.expects(:contact)
    User.expects(:new).with("Kirk", "kirk@metallica.com").returns(user)
    Account.create("Kirk", "kirk@metallica.com")
  end
end
</pre>
<p>As an alternative, and this is the version I see most often used, a duck typed mock can be used in the place of the &#8220;real&#8221; <code>User</code> object.</p>
<pre>
class AccountTest &lt; Test::Unit::TestCase
  def test_emails_user_on_account_creation
    user = mock
    user.expects(:contact)
    User.expects(:new).with("Kirk", "kirk@metallica.com").returns(user)
    Account.create("Kirk", "kirk@metallica.com")
  end
end
</pre>
<p>Both implementations have some potentially undesirable issues worth taking into consideration. None of the two is <acronym title="Don't Repeat Yourself">DRY</acronym>, since in both cases we need to set a bespoke expectation for the object&#8217;s instantiation. In the first example, we are actually instantiating a &#8220;real&#8221; <code>User</code>. This compromises the dependency neutrality of the test, coupling it with <code>User</code>&#8217;s initialization implementation. The second example, despite its relative convenience, doesn&#8217;t fully respect the contract between <code>Account</code> and <code>User</code>. The interaction specification is inaccurate, because, as far as the application code under test is concerned, <code>User#new</code> doesn&#8217;t return an object of type <code>Mocha::Mock</code>, it returns an instance of <code>User</code>.</p>
<p>The following code can be useful in an effort to DRY up code as the one under discussion, whilst driving such interaction specifications closer to the actual contracts they are meant to express.</p>
<pre>
class Object
  def self.mock_instance(*args)
    class_eval do
      alias original_initialize initialize
      def initialize()end
    end

    instance = new
    expects(:new).with(*args).returns(instance)

    class_eval do
      alias initialize original_initialize
      undef original_initialize
    end

    return instance
  end
end
</pre>
<p>Here is how <code>AccountTest</code> can be written with the above <a href="http://mocha.rubyforge.org/" title="Mocha 0.5.6">Mocha</a> extension in place.</p>
<pre>
class AccountTest &lt; Test::Unit::TestCase
  def test_emails_user_on_account_creation
    User.mock_instance("Kirk", "kirk@metallica.com").expects(:contact)
    Account.create("Kirk", "kirk@metallica.com")
  end
end
</pre>
<p>If <a href="http://rspec.info/" title="RSpec-1.1.3: Overview">RSpec</a> is your flavor, the same can be achieved with minor modifications in the <code>Spec::Mocks::Methods</code> module.</p>
<pre>
module Spec::Mocks::Methods
  def mock_instance(*args)
    class_eval do
      alias original_initialize initialize
      def initialize()end
    end

    instance = new
    should_receive(:new).with(*args).and_return(instance)

    class_eval do
      alias initialize original_initialize
      undef original_initialize
    end

    return instance
  end
end
</pre>
<p>With the above we can use <code>mock_instance</code> in specs as such.</p>
<pre>
describe Account do
  it "should email user on account creation" do
    User.mock_instance("Kirk", "kirk@metallica.com").should_receive(:contact)
    Account.create("Kirk", "kirk@metallica.com")
  end
end
</pre>
]]></content:encoded>
			<wfw:commentRss>http://nutrun.com/weblog/ruby-mock-instance/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Event registry</title>
		<link>http://nutrun.com/weblog/event-registry/</link>
		<comments>http://nutrun.com/weblog/event-registry/#comments</comments>
		<pubDate>Tue, 22 Apr 2008 00:27:05 +0000</pubDate>
		<dc:creator>George Malamidis</dc:creator>
		
		<category><![CDATA[Software]]></category>

		<guid isPermaLink="false">http://nutrun.com/?p=135</guid>
		<description><![CDATA[During projects I&#8217;ve worked on which involved coding JavaScript, I&#8217;ve had positive experiences enjoying the event driven nature of the language and some bad, especially after code bases grew larger with events firing left and right, producing side effects which were difficult to manage or track down. During the bad days, a centralized way of [...]]]></description>
			<content:encoded><![CDATA[<p>During projects I&#8217;ve worked on which involved coding JavaScript, I&#8217;ve had positive experiences enjoying the event driven nature of the language and some bad, especially after code bases grew larger with events firing left and right, producing side effects which were difficult to manage or track down. During the bad days, a centralized way of managing events was often brought up in conversations with colleagues as a means of managing the issue.</p>
<p>I&#8217;ve long been a fan of the event driven style of programming as a particularly useful alternative promoting loose coupling of system components. Below is the code for a Ruby module which, when included, enables classes to act as event dispatchers. Other classes can subscribe to the events and be notified when an event occurs.</p>
<pre>
module EventDispatcher
  module ClassMethods
    attr_reader :listeners

    def subscribe(event, &amp;callback)
      @listeners ||= {}
      (@listeners[event] || @listeners[event] = []) &lt;&lt; callback
    end

    private

    def clear_listeners!
      @listeners = {}
    end
  end

  def self.included(receiver)
    receiver.extend(ClassMethods)
  end

  def notify(event, *args)
    self.class.listeners[event].each {|callback| callback[*args]}
  end
end
</pre>
<p>Let&#8217;s consider an example application where the resource management department of an organization hires recruits and upon admission notifies interested services to take relevant action.</p>
<pre>
class RM
  include EventDispatcher

  def hire(name)
    notify(:new_recruit, name)
  end
end
</pre>
<p>What is especially interesting here is how the <code>RM</code> class doesn&#8217;t need to know anything about any interested listeners. In order to test <code>RM</code>, it suffices to ensure that a notification is sent upon calling the <code>hire</code> method.</p>
<pre>
def test_rm_notifies_on_new_hire
  service = mock
  service.expects(:new_recruit).with("name")
  RM.subscribe(:new_recruit) {|name| service.new_recruit(name)}
  RM.new.hire("name")
end
</pre>
<p>Typically, listeners would directly register their interest to the event by subscribing to it. Let&#8217;s imagine a welcoming letter is issued to new recruits the moment they join the organization.</p>
<pre>
class WelcomeLetterService
  RM.subscribe(:new_recruit) {|name| greet(name)}

  def self.greet(name)
    "Welcome, #{name}!"
  end
end
</pre>
<p>The first thing to notice is <code>WelcomeLetterService</code>&#8217;s direct coupling to <code>RM</code>. Additionally, a code base heavily employing this strategy might suffer ill effects similar to the ones described in the JavaScript inspired first paragraph of this article. Allowing a centralized option for event registration and management could serve as possible remedy to the issue.</p>
<pre>
module EventRegistry
  def register_event_listeners
    RM.subscribe(:new_recruit) {|name| WelcomeLetterService.greet(name)}
  end

  extend self
end
</pre>
<p>The <code>EventRegistry</code> module acts as a centralized mechanism for declaring which listeners subscribe to which events. On top of that, the <code>WelcomeLetterService</code> is now completely oblivious to the <code>RM</code> class.</p>
<pre>
class WelcomeLetterService
  def self.greet(name)
    "Welcome, #{name}!"
  end
end
</pre>
<p>Due to the level of decoupling achieved, testing these two components becomes particularly easy.</p>
<pre>
def test_welcome_letter_service_greets_by_name
  assert_equal(WelcomeLetterService.greet("Name"), "Welcome, Name!")
end

def test_event_subscription_wiring
  WelcomeLetterService.expects(:greet).with("name")
  RM.expects(:subscribe).with(:new_recruit).yields("name")
  EventRegistry.register_event_listeners
end
</pre>
<p>All this ties well with the philosophy behind <a href="http://synthesis.rubyforge.org/" title="synthesis">Synthesized Testing</a>, where a coherent collection of lightweight tests becomes a major factor of confidence that the system under test is complete, reducing the need for complex overarching tests.</p>
]]></content:encoded>
			<wfw:commentRss>http://nutrun.com/weblog/event-registry/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Erubis with Sinatra</title>
		<link>http://nutrun.com/weblog/erubis-with-sinatra/</link>
		<comments>http://nutrun.com/weblog/erubis-with-sinatra/#comments</comments>
		<pubDate>Sun, 20 Apr 2008 01:20:52 +0000</pubDate>
		<dc:creator>George Malamidis</dc:creator>
		
		<category><![CDATA[Software]]></category>

		<guid isPermaLink="false">http://nutrun.com/?p=134</guid>
		<description><![CDATA[
	Sinatra doesn&#8217;t yet seem to come with built in support for Erubis. If you want the relative speed bump of Erubis over standard ERB for your Sinatra application, the code below should do the trick.


module Sinatra::Erb
  def erb(content, options={})
    begin
      require 'erubis'
     [...]]]></description>
			<content:encoded><![CDATA[<p>
	<a href="http://sinatrarb.com/" title="Nancy">Sinatra</a> doesn&#8217;t yet seem to come with built in support for <a href="http://www.kuwata-lab.com/erubis/" title="Erubis: fast and extensible eRuby implementation">Erubis</a>. If you want the relative speed bump of Erubis over standard ERB for your Sinatra application, the code below should do the trick.
</p>
<pre>
module Sinatra::Erb
  def erb(content, options={})
    begin
      require 'erubis'
      @@erb_class = Erubis::Eruby
    rescue LoadError
      require "erb"
      @@erb_class = ::ERB
    end
    render(:erb, content, options)
  end

  private

  def render_erb(content, options = {})
    @@erb_class.new(content).result(binding)
  end
end
</pre>
<p>Application code will not require any modifications, Sinatra will use Erubis if the gem is found in the load path.</p>
]]></content:encoded>
			<wfw:commentRss>http://nutrun.com/weblog/erubis-with-sinatra/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Merb: render_deferred and render_then_call</title>
		<link>http://nutrun.com/weblog/merb-render_deferred-and-render_then_call/</link>
		<comments>http://nutrun.com/weblog/merb-render_deferred-and-render_then_call/#comments</comments>
		<pubDate>Thu, 17 Apr 2008 23:23:31 +0000</pubDate>
		<dc:creator>George Malamidis</dc:creator>
		
		<category><![CDATA[Software]]></category>

		<guid isPermaLink="false">http://nutrun.com/?p=133</guid>
		<description><![CDATA[
	Following the post on non blocking merb actions, it&#8217;s worth mentioning the Merb::ControllerMixin module, its render_deferred and render_then_call methods in particular.


	render_deferred accepts a block argument, a proc that will be called outside the dispatch mutex, releasing the merb thread lock.


class MyController &#60; Merb::Controller
  def hello
    render "hello"
  end

  def [...]]]></description>
			<content:encoded><![CDATA[<p>
	Following the post on <a href="http://nutrun.com/weblog/non-blocking-merb-actions/" title="nutrun  &raquo; Blog Archive   &raquo; Non blocking merb actions">non blocking merb actions</a>, it&#8217;s worth mentioning the <a href="http://www.merbivore.com/documentation/merb-core/0.9.2/index.html?a=C00000080&amp;name=ControllerMixin" title="Merb | merb-core 0.9.2 API Documentation">Merb::ControllerMixin</a> module, its <code>render_deferred</code> and <code>render_then_call</code> methods in particular.
</p>
<p>
	<code>render_deferred</code> accepts a block argument, a <code>proc</code> that will be called outside the dispatch <code>mutex</code>, releasing the merb thread lock.
</p>
<pre>
class MyController &lt; Merb::Controller
  def hello
    render "hello"
  end

  def dont_wait_to_hello
    render_deferred { VerySlow.hello }
  end
end
</pre>
<p>
Calls to <code>/my_controller/hello</code>, subsequent to requests to <code>/my_controller/dont_wait_to_hello</code>, will not have to wait for the latter to complete before being served.
</p>
<p>
	As an interesting caveat, because execution of the <code>proc</code> is outside merb&#8217;s control, any exceptions raised in the block passed to <code>render_deferred</code> will not be rescued and redispatched, which suggests that custom error handling needs to be in place.
</p>
<p>
	<code>render_then_call</code> accepts two arguments, a string that will be returned immediately as a response to the client and a block to be called after the string has been returned.
</p>
<pre>
class MyController &lt; Merb::Controller
  def receive_order
    render_then_call("Your pizza is in the oven.") do
      bake_pizza
      deliver_pizza
    end
  end
end
</pre>
<p>In this case, the specified message will be immediately returned, while the long running <code>proc</code> will be scheduled and executed by Mongrel, allowing orders to keep coming through a single application instance.</p>
]]></content:encoded>
			<wfw:commentRss>http://nutrun.com/weblog/merb-render_deferred-and-render_then_call/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Non blocking merb actions</title>
		<link>http://nutrun.com/weblog/non-blocking-merb-actions/</link>
		<comments>http://nutrun.com/weblog/non-blocking-merb-actions/#comments</comments>
		<pubDate>Wed, 16 Apr 2008 00:22:50 +0000</pubDate>
		<dc:creator>George Malamidis</dc:creator>
		
		<category><![CDATA[Software]]></category>

		<guid isPermaLink="false">http://nutrun.com/?p=132</guid>
		<description><![CDATA[One of the most powerful features in merb is an action&#8217;s ability to return a proc, thus releasing the controller block and transferring control to the application server which will be able to handle requests in a parallel manner.
Consider the following controller.

class MyController &#60; Application
  def hello
    render "hello"
  end

 [...]]]></description>
			<content:encoded><![CDATA[<p>One of the most powerful features in <a href="http://www.merbivore.com/" title="Merb | Looking for a better framework?">merb</a> is an action&#8217;s ability to return a <code>proc</code>, thus releasing the controller block and transferring control to the application server which will be able to handle requests in a parallel manner.</p>
<p>Consider the following controller.</p>
<pre>
class MyController &lt; Application
  def hello
    render "hello"
  end

  def wait_and_hello
    sleep 10
    render "hello"
  end

  def dont_wait_to_hello
    proc { sleep 10; p "hello" }
  end
end
</pre>
<p>Start merb and access <code>http://localhost:4000/my_controller/hello</code> after visiting <code>http://localhost:4000/my_controller/wait_and_hello</code>. Ten seconds will pass before <code>/my_controller/hello</code> is served. A request to <code>/my_controller/hello</code> will be served immediately regardless of whether a preceding request to <code>/my_controller/dont_wait_to_hello</code> has completed.</p>
]]></content:encoded>
			<wfw:commentRss>http://nutrun.com/weblog/non-blocking-merb-actions/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Thin, Mongrel, Rack and performance</title>
		<link>http://nutrun.com/weblog/thin-mongrel-rack-and-performance/</link>
		<comments>http://nutrun.com/weblog/thin-mongrel-rack-and-performance/#comments</comments>
		<pubDate>Thu, 03 Apr 2008 22:18:17 +0000</pubDate>
		<dc:creator>George Malamidis</dc:creator>
		
		<category><![CDATA[Software]]></category>

		<guid isPermaLink="false">http://nutrun.com/?p=130</guid>
		<description><![CDATA[
	I just ran a crud and unscientific test to satisfy my curiosity in regards to the speed difference between Thin and Mongrel.


	I used Rack for convenience. This probably skews the results.


require "rubygems"
require "rack"

def run(server)
  require server
  s = Rack::Handler.const_get("#{server.capitalize}")
  app = proc {&#124;env&#124; [200, {"Content-Type" => "text/plain"}, "hello"]}
  s.run(app,:Host => '127.0.0.1', [...]]]></description>
			<content:encoded><![CDATA[<p>
	I just ran a crud and unscientific test to satisfy my curiosity in regards to the speed difference between <a href="http://code.macournoyer.com/thin/" title="Thin - yet another web server">Thin</a> and <a href="http://mongrel.rubyforge.org/" title="Mongrel - Trac">Mongrel</a>.
</p>
<p>
	I used <a href="http://rack.rubyforge.org/" title="Rack: a Ruby Webserver Interface">Rack</a> for convenience. This probably skews the results.
</p>
<pre>
require "rubygems"
require "rack"

def run(server)
  require server
  s = Rack::Handler.const_get("#{server.capitalize}")
  app = proc {|env| [200, {"Content-Type" => "text/plain"}, "hello"]}
  s.run(app,:Host => '127.0.0.1', :Port => 2323)
end

run "thin"
# run "mongrel"
</pre>
<p>
	I wrote a simple HTTP client sending one thousand consecutive, <em>non simultaneous</em> requests.
</p>
<pre>
require "net/http"

before = Time.now
1000.times {Net::HTTP.new('127.0.0.1', 2323).request_get('/')}
p "#{1000/(Time.now - before)} requests per second"
</pre>
<p>
	The results&#8230; Thin did around 1160 requests per second, whereas Mongrel did 1220 on average.
</p>
<p>
	Interestingly, when I added <code>Rack::Lint</code> to the mix, Thin dropped to about 640 requests per second and Mongrel dropped to 685.
</p>
<pre>
s.run(Rack::Lint.new(app),:Host => '127.0.0.1', :Port => 2323)
</pre>
<p>
	Bearing in mind that these are non concurrent requests and that I&#8217;m running both the server and client on my Laptop (a 2.2 GHz 2GB RAM MacBook Pro) and that Rack is included in the stack, it seems that Mongrel has outperformed Thin. The most interesting, albeit accidentally discovered, observation however is the grave hit on performance noted when <code>Rack::Lint</code> becomes part of the equation.</p>
]]></content:encoded>
			<wfw:commentRss>http://nutrun.com/weblog/thin-mongrel-rack-and-performance/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Nu Language Event Dispatcher</title>
		<link>http://nutrun.com/weblog/nu-language-event-dispatcher/</link>
		<comments>http://nutrun.com/weblog/nu-language-event-dispatcher/#comments</comments>
		<pubDate>Tue, 01 Apr 2008 15:17:36 +0000</pubDate>
		<dc:creator>George Malamidis</dc:creator>
		
		<category><![CDATA[Software]]></category>

		<guid isPermaLink="false">http://nutrun.com/?p=129</guid>
		<description><![CDATA[
	Nu is an interpreted object oriented language built on top of Objective C, with its syntax and several of its mechanics coming from Lisp, whilst being inspired by Ruby&#8217;s philosophy.


	 The Event Dispatcher example is one of my favorite when trying out a new language. I choose it because it&#8217;s representative of a number of [...]]]></description>
			<content:encoded><![CDATA[<p>
	<a href="http://programming.nu/" title="Programming Nu">Nu</a> is an interpreted object oriented language built on top of Objective C, with its syntax and several of its mechanics coming from Lisp, whilst being inspired by Ruby&#8217;s philosophy.
</p>
<p>
	 The <em>Event Dispatcher</em> example is one of my favorite when trying out a new language. I choose it because it&#8217;s representative of a number of programming language core topics such as lists, maps, closures, OO, etc.
</p>
<p>
	I recently spent a short while porting the <a href="http://nutrun.com/weblog/io-language-event-dispatcher/" title="nutrun  &raquo; Blog Archive   &raquo; IO Language Event Dispatcher">IO Language Event Dispatcher example</a> in Nu and will be going over my experiment in this article.
</p>
<p>
	Bellow is the code for the <code>EventDispatcher</code> class.
</p>
<pre>
(class EventDispatcher is NSObject
  (- (id) initialize is
    (set @listeners (dict))
      self)

  (- (void) subscribe:(id)event callback:(id)callback is
    (unless (@listeners objectForKey:event)
      (@listeners setObject:(array) forKey:event))
      ((@listeners objectForKey:event) &lt;&lt; callback))

  (- (void) notify:(id)event withArgs:(id)args is
    ((@listeners objectForKey:event) each: (do
      (callback) (callback args)))))
</pre>
<p>
	There are two prominent methods in this class, namely <code>subscribe</code> and <code>notify</code>.
</p>
<p>
	The <code>subscribe</code> method takes two arguments, the event we&#8217;re subscribing to and a callback to be invoked every time the specified event takes place. The <code>@listeners</code> dictionary is constructed using the <code>dict</code> directive, which is shorthand for creating an <code>NSCFDictionary</code> instance. For each event, we maintain an array of callbacks. Like <code>dict</code>, <code>array</code> is available for conveniently creating <code>NSCFArray</code> instances.
</p>
<p>
	Whenever <code>notify</code> is invoked with an event and the relevant arguments, we iterate invoking any callbacks registered for the given event, passing the provided arguments to each.
</p>
<p>
	There are two ways that I know of that will allow classes to act as event dispatchers, inheritance being the first.
</p>
<pre>
(class Factory is EventDispatcher
  (ivars)

  (- (void) produce:(id)color is
    (puts "#{color} product produced")
    (self notify:"new product" withArgs:color)))
</pre>
<p>
	Here, we create a <code>Factory</code> class which extends <code>EventDispatcher</code> and we define a <code>produce</code> method which notifies listeners that have subscribed to the &#8220;new product&#8221; event.
</p>
<p>
	Composition is the second, and my preferred, option.
</p>
<pre>
(class Factory is NSObject
  (ivars)

  (- (void) produce:(id)color is
    (puts "#{color} product produced")
    (self notify:"new product" withArgs:color)))

(Factory include:EventDispatcher)
</pre>
<p>
	Classes in Nu can be used in a manner similar to that of Module mix-ins in Ruby. Every object in Nu has an <code>include</code> method which will make a class&#8217;s instance methods available in another class. The advantage here is that we didn&#8217;t have to change <code>Factory</code>&#8217;s inheritance tree.
</p>
<p>
	Following is a potential event listener that subscribes to the &#8220;new product&#8221; event and prints out a message every time the event is fired.
</p>
<pre>
(class ProductWatcher is NSObject
  (- (id) watch is
    (factory subscribe:"new product" callback:(do (color)
      (puts "I see a #{color} product")))))
</pre>
<p>
	To run the example, we can instantiate a <code>Factory</code> and a <code>ProducWatcher</code> and fire a few events.
</p>
<pre>
(set factory ((Factory new) initialize))
((ProductWatcher new) watch)

(factory produce:"black")
(factory produce:"red")
(factory produce:"blue")
</pre>
<p>
The results look like this:
</p>
<pre>
black product produced
I see a black product
red product produced
I see a red product
blue product produced
I see a blue product
</pre>
<p>
There are a lot of reasons as to why I have time for Nu, its combining 3 of my favorite languages not included, greatly simplifying Cocoa development for native Mac and iPhone applications and Objective C&#8217;s excellent multi-core support to name but a few.</p>
]]></content:encoded>
			<wfw:commentRss>http://nutrun.com/weblog/nu-language-event-dispatcher/feed/</wfw:commentRss>
		</item>
	</channel>
</rss>
