Bringing web applications to your Desktop with Prism

 Aug, 22 - 2009   3 comments   Web

I have almost finished working on a web app that will be used inside intranets by students willing to do their English language exams interactively. I have reached the point where I want the app to have as much as possible the look of a desktop one. So I started thinking that may be with the help of Javascript I might be able to remove the browser toolbar; not a bad idea so far. Also I wanted to disable both back and refresh buttons because the exam is timed and the student will have a time counter for each section. However after I ran through this thread and found a strong resistance towards such ideas, I decided to go with other solution. Simply I chose to remove the toolbar and use keystroke events to determine which ones are related to navigation, just like ‘f5′ and ‘backspace’. So far so good, but after few minutes of work on this approach, I had few thoughts at mind: “Why am I doing so? Do I really need a browser to do this? shouldn’t be there any software that can render HTML markup and can have a customized interface?”
I start searching for such a software and found Prism, which is a cool product by Mozilla that helps you turning a web app into a desktop like one. Taken from the product why page:

Instead of running all your web apps in the browser, Prism lets you run them in their own window just like normal applications. A single faulty app or web page can no longer take down everything you are working on.

Prism is so easy to be used, it takes 1 minute approximately to turn your web app into a desktop one and you will gain many Desktop integration things like:

  • Access web apps from system taskbar or dock
  • Tray icon and dock menus
  • Associate applications with browser links
  • Minimize to tray
  • System tray icon and dock badges

Prism can be used as a stand alone soft, or just another Firefox addon(this one didn’t play well with me). Give it a shoot, you won’t regret it!

Observer and Singleton design patterns in Ruby

 Aug, 21 - 2009   13 comments   Design PatternsRuby

This is my first article in, it was published in issue 3, so basically I’m just republishing it here again.

Observer and singleton are two common design patterns that a programmer should be familiar with, however what made me write about them, is that both are there out of the box for you to use in ruby.
So let’s have a look at both and see how ruby help you use them directly:

Observer Design Pattern

According to Wikipedia:

The observer pattern (sometimes known as publish/subscribe) is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods. It is mainly used to implement distributed event handling systems.

So how does ruby help you implementing this design pattern? Well, the answer is by mixing the observable module into your subject (observed object).
Let’s take an example, let’s suppose we have a banking mechanism that notifies the user by several ways upon withdrawal operations that leaves the account with balance less or equal to $0.5.
If we look deeply at this problem, we can qualify it as a good candidate for observer design pattern, where the bank account is our subject and the notification system as the observer.
Here is a code snippet for this problem and it’s solution:

So to user ruby observer lib we have to implement four things:
1- Require the ‘observer’ lib and include it inside the subject (observed) class.
2- Declare the object to be ‘changed’ and then notify the observers when needed – just like we did in ‘withdraw’ method.
3- Declare all needed observers objects that will observe the subject.
4- Each observer must implement an ‘update’ method that will be called by the subject.

Observers in Rails

You can find observers in rails when using ActiveRecord, it’s a way to take out all ActiveRecord callbacks out of the model, for example a one would do this:

A neater solution is to use Observers:

You can generate the previous observer using the following command:

You still can have observers that map to models that don’t match with the observer name using the ‘observe’ class method, you also can observe multiple models using the same method:

Finally don’t forget to add the following line inside config/environment.rb to define observers:

Singleton Design Pattern

According to Wikipedia:

In software engineering, the singleton pattern is a design pattern that is used to restrict instantiation of a class to one object. (This concept is also sometimes generalized to restrict the instance to a specific number of objects – for example, we can restrict the number of instances to five objects.) This is useful when exactly one object is needed to coordinate actions across the system.

The singleton design pattern is used to have one instance of some class, typically there are many places where you might want to do so, just like having one database connection, one LDAP connection, one logger instance or even one configuration object for your application.
In ruby you can use the singleton module to have the job done for you, let’s take ‘application configuration’ as an example and check how we can use ruby to do the job:

So what does ruby do when you include the singleton method inside your class?
1- It makes the ‘new’ method private and so you can’t use it.
2- It adds a class method called instance that instantiates only one instance of the class.
So to use ruby singleton module you need two things:
1- Require the lib ‘singleton’ then include it inside the desired
2- Use the ‘instance’ method to get the instance you need.

Ruby 1.9 Encoding Fun

 Jul, 13 - 2009   4 comments   Ruby

Ruby 1.9 has a great support for encoding, this post covers that for a big deal, however with this support out of the box, things like this becomes easier, just note the source code is not limited to few types of encoding just like Ruby 1.8.

Please note that previous example could work also with Ruby 1.8 using the flag -Ku, I just wanted to explain the idea of using different types of encoding in Ruby 1.9.

So all you need to do is to set whatever encoding you want for your source code at the very beginning of the file:

Many other things can be done, just give yourself a moment and think what you can do!

Scala is my next choice

 Jul, 12 - 2009   31 comments   Scala

I have done Pascal, C, C++, Java, PHP, Ruby, Groovy and recently Scala, which I found it to be a unique language compared to anything else I have ever worked with. My journey with this language started after the Twitter’s Ruby vs Scala debate. Now and after few months of work with this language I really want to share you two ideas that are no secrets anymore:

  • Scala Does Rock.
  • I do believe this language should be taught in CS colleges and institutes.

I’m going to justify my opinion during this article, just before doing so I have few notes I feel like I have to address:

  • This article is not to compare languages, it’s to address why you should learn Scala.
  • Scala has 2 implementations right now, one that runs on the JVM, and one that runs on the CLR. However the JVM one is more mature, and I believe it’s better to stick to the advice of David Pollack(Lift framework creator) to use F# if you want to work with .Net framework. However I will stick to JVM implementation in this article.
  • I’m a Rubiest, and I still like Ruby cause it’s the best dynamic language ever, but I like Scala also because it has some features that are so powerful for other work domains.

Now, let’s dive into the some reasons that’s makes Scala my next language of choice:

A hyper language

Scala is a hyper language that enables you to code in imperative and functional paradigms, so you can code with the normal imperative style just like we do in C, Java, PHP and many other languages, or you can code in a functional style like we do in Lisp for example, or you can mix both, just like we do in Ruby or Groovy.

However, one distinct to Ruby and Groovy when talking about the functional paradigm, is that Scala almost supports all known features of functional languages, like Pattern matching, Lazy initialization, Partial Functions, Immutability, etc…

That’s said, it’s important to address the fact that the power of Scala comes from it’s support for the functional paradigm, which makes the language a high-level one. A high-level language makes you focus on ‘what’ to do rather than ‘how’ to do.

Look at this Java example:

If you focus on the previous example, you will notice that the ‘what’ part of what I want to do (Filtering odd values) comes on the 4th line, and the other lines are just the ‘how’ part of it(result var initialization and a loop), thus if I want to write another filter for even numbers, It will take me another 5 lines to do the same, while in a high-level languages like Scala, you will need to express the ‘what’ part only:

Notice how the previous code snippet is more readable and more concise than the Java equivalent.


Scala is an efficient language, actually due to the latest benchmarks Scala is almost as fast as Java. The JVM implementation of Scala compiles down to bytecode, but during so, the code passes through optimization phaze. An optimization example is the tail recursion optimization, to help you stick to the functional paradigm without sacrificing the performance. Another example is the optimization done to convert Scala value type objects to Java primitive types.


The name of Scala language comes form the word ‘Scalable’, meaning that this language grows with the demand of its users. So basically you can add new type and control structures. For example I want to add a simple ‘loop’ control structure:

A more comprehensive example is the Actor lib, which is added as an extension to the language, we will talk about it later on.

However what makes Scala Scalable is two related things: being pure object oriented and being functional.

Object Oriented

  • Everything in Scala is an object(except for the objects’ methods), so there is no need to differentiate between primitive or reference types, this is called: Uniform Object Model. But as I mentioned earlier during the optimization process, value type objects are converted to Java primitive types, so don’t be worried about the performance.
    There are also singleton objects to group class methods inside them.
  • All operations are method calls, + - * ! / all are methods, so there no need for operator overloading.
  • A great fine-grained access control, where you can control access for certain methods for certain packages also.
  • Scala has traits, similar to mixins in Ruby, which are like interfaces in Java but have some of their methods implemented, thus you can have rich wrappers and interfaces out of the box.


A functional language has many characteristics, however what we care for in our Scalability context is 2 facts:

Functions are first-class values

Which means that you can pass them as values and return them as values as well. This leads to concise readable code just like the filtering examples mentioned above.

Pure functions

Scala encourages pure functions that have no side effects, meaning: when you have the same input, you will always have the same output. This will result in safer and easier to test code.
But how does Scala encourages pure functions? By immutability: Favoring fixed references(like final in java or constants in other languages) and having immutable data structures that once created can’t be modified.

Immutability is the safe guard to have pure functions, but it’s not the only way. You still can write safe code without immutability. That’s why Scala doesn’t force immutability but it encourages it. Eventually you will find that many data structures in Scala have 2 implementations, one is mutable and the other is immutable, immutable data structures are imported by default.

Some concerns regarding performance might arise when talking about immutability, and while these concerns are valid in this context, it turned out that things are somehow reversed when it comes to Scala. Immutable data structures tend to be more efficient than mutable ones. One reason for that is the existence of a robust garbage collector like the one of JVM. You can find more information about the efficiency of immutable data structures in Scala in this blog post.

Better concurrency model

When it comes to threading, Scala supports the traditional shared data model. However and after long experiments with this model, many people found it to be so hard to to implement and test concurrent code written using this model. You will always have to consider deadlocks and race conditions. Thus Scala suggests another concurrency model called Actors, where an actor sends and receives asynchronous messages in it’s inbox instead of sharing data. This is called: shared nothing model. Once you stop thinking about shared data, you relief yourself from the headache of thinking of code synchronization and deadlocks problems.

Together the immutability nature of the sent messages and the serial processing of messages in the actor, leads to easier concurrency support.
There are 2 articles(1,2) on the IBM developerWorks website that cover Scala concurrency deeply. Please refer back to them to have a better idea about this topic.

Before I move to the next point I need to mention the fact that some people consider the use of Actors as an evolutionary progress in programming languages. As Java came and relieved programmers from the headache of pointers and memory management, Scala came to relief programmers from thinking all the time of code synchronization and the problems raised by shared data model.

Statically typed

When i wanted to cover this point, I found myself trying to weigh both the pros and cons of a statically typed language. Actually there is an endless debate regarding this topic but I tried to sum things up to two points that I found most people talking about:

Code written in statically typed languages is more robust

It’s true that with the existence of TDD most of the talk about dynamically typed systems and robust code starts to lose its value, but one fact still exists: in dynamically typed languages you write more tests to check types, while in statically typed ones, you leave things out for the compiler. Also some people argue that with a statically typed language you have a better self documenting code.

Code written in statically typed languages is so strict and verbose

Fans(just like me) of dynamically typed languages argue that they can produce more dynamic code structures through duck typing. Also they complain about the verbosity introduced with statically typed languages.

You can read more about static versus dynamic typing here.

Scala as a statically typed language will gain the first point, but how about the second one?
Scala has a flexible type system, and may be the best of it’s type. So in many cases this system will be able to infer the type in case you didn’t specify it.
For example you can do this:

But you can do this also:

Well, that’s cool as it solves the verbosity problem somehow. But what about things like duck typing?
Again: Scala’s type system has some flexibility that enables you to do things like:

Where we define the Type T to be a sub type of Animal. It can be more flexible even:

Where we define the type T to be a type that has the method eat.
Actually Scala’s type system is so rich, you can find more about that here.

Pattern matching

I have to admit that I hesitated a lot to write about this feature, actually I didn’t want to cover functional features of Scala, but after I read this specific post regarding switch use with objects, I thought it’s good to talk about this feature.
So basically and taken from this post :

So what does pattern matching do? It lets you match a value against several cases, sort of like a switch statement in Java. But instead of just matching numbers, which is what switch statements do, you match what are essentially the creation forms of objects.

And the following example:

In the first case, the pattern Name(first, last) is nested inside the pattern Address(…). The last value, which was passed to the Name constructor, is “extracted” and therefore usable in the expression to the right of the arrow.


The purpose of pattern matching

So why do you need pattern matching? We all have complicated data. If we adhere to a strict object-oriented style, then we don’t want to look inside these trees of data. Instead, we want to call methods, and let the methods do the right thing. If we have the ability to do that, we don’t need pattern matching so much, because the methods do what we need. But there are many situations where the objects don’t have the methods we need, and we can’t (or don’t want to) add new methods to the objects.

So, Pattern matching is considered a valid way of extensibility, and it offers a great solution to this problem apart from the verbosity that comes with Visitor design pattern.

Anyway, it’s highly recommended that you read the “Two directions of extensibility” in the previous mentioned article.

Easy DSLs

Scala is very good for coding DSLs. Actually Scala is suitable for both Internal and external DSLs. You can find in this article a little comparison of features between Ruby and Scala for writing internal DSLs. Check this cool post on internal DSLs using Scala: Boolean Algebra Internal DSL in Scala (aka fun with Unicode names ).
Also when it comes to External DSLs, Scala should be your first choice, and the reason behind that is the parser combinator lib, that makes writing compilers for new languages is really cool. You’d better follow this cool post to get a better idea about what Scala can do.

Interoperable with Java code

The JVM implementation of Scala have seamless integration with Java platform, actually many Scala types compiles down to Java types, so you can use Java libs safely. Also you can make some work between JVM languages like JRuby, Groovy, Clojure and others.
Here is a good post with examples.

Educational language

I had 2 habits that I kept practicing during the learning curve of Scala :

Both of these two habits made me gain more knowledge and increased the quality of my code through some good practices like: writing pure methods that has no side effect and focusing on the ‘what’ part of my code, leaving the ‘how’ one to language abstractions..


Scala was designed by Martin Odersky the man running the Programming Methods Laboratory (LAMP) group at Swiss Federal Institute of Technology in Lausanne (EPFL). Odersky was approached by Sun to write the Java 1.1 compiler, he was the lead developer of javac from Java 1.1 through Java 1.4. Also he is the guy behind Java Generics.
Scala is being maintained by Odersky and his team at EPFL. However there are other talented folks who helped shaping Scala over years, you can check the full list here.


Scala was inspired by many languages:

  • Most of the syntax is coming from Java and C#.
  • Other elements where adopted from Java such as: basic types, class libraries, and its execution model.
  • Its uniform object model was pioneered by Smalltalk.
  • Its idea of universal nesting is also present in Algol, Simula, and, more recently in Beta and gbeta.
  • Its uniform access principle for method invocation and field selection comes from Eiffel.
  • Its approach to functional programming is quite similar in spirit to the ML family of languages, which has SML, OCaml, and F# as prominent members.
  • Many higher-order functions in Scala’s standard library are also present in ML or Haskell.
  • Scala’s implicit parameters were motivated by Haskell’s type classes. Scala’s actor-based concurrency library was heavily inspired by Erlang.
  • The specific idea of treating an infix operator as a function and permitting a function literal (or block) as a parameter, which enables libraries to define control structures can be traced back to Iswim and Smalltalk.

Experts’ Opinions

This article is a very good one showing some for experts’ opinions regarding Scala language. Actually it has some surprises like James Strachan’s(creator of Groovy language) statement:

I can honestly say if someone had shown me the Programming in Scala book by Martin Odersky, Lex Spoon & Bill Venners back in 2003 I’d probably have never created Groovy

Also I have found these interviews to be very useful:

At the end of this point I like to sum things up:
I like Scala because it’s efficient, educational, has better concurrency model, and very good for writing DSLs.
I also want to share another secret with you:
I’m planning to write a book on Scala language, I have an idea at mind and would like to coauthor with any guy from the Scala camp, please ping me if you have the same attention as mine.

Real World Examples


Ruby Currying

 May, 24 - 2009   8 comments   Functional ProgrammingRuby

Update: This post was updated to show the difference between Currying and Partial Functions.
Currying is a concept in Functional Programming that’s enabled by Higher-order functions. It’s best described as: the ability to take a function that accepts n parameters and turns it into a composition of n functions each of them take 1 parameter. Check this function f which takes 3 params x,y,z

f(x,y,z) = 4*x+3*y+2*z

Currying means that we can rewrite the function as a composition of 3 functions(a function for each param):

f(x)(y)(z) = 2*z+(3*y+(4*x))

The direct use of this is what is called Partial Function where if you have a function that accepts n parameters then you can generate from it one of more functions with some parameter values already filled in. Ruby 1.9 comes with support for currying concept(through the Proc#curry method) and this blog post is explaining how you can use it effectively.
I’m going to walk you through a simple example to explain the concept, however i need to mention few things:
1- The main example is taken from the free Scala By Example book(First-Class Functions chapter), however i have replaced recursion calls by simple upto iterators.
2- In Ruby 1.9 you can use block.(*args) just like you use*args) or block[*args] in Ruby 1.8, so i’ll stick to block.(*) notation.
3- I could have used the inject method, but i preferred readability to concise code.

Let’s start the simple tutorial by adding three methods:
1- A method to sum all integers between two given numbers a and b.
2- A method to sum the squares of all integers between two given numbers a and b.
3- A method to to sum the powers 2^n of all integers n between two given numbers a and b.

Cool, however if you focus on the 3 methods, you will notice that these methods are all instances of a pattern Σf(n) for a range of values a -> b. We can factor out the common pattern by defining a method sum:

Ok, but what about having the formal definitions for the 3 methods? How can we have those definitions out of the sum method? Well that’s the use of currying and partial functions, in our case we just need to pass the first param to the sum method to specify what type of sum is it:

That’s it! I hope I could clarify the use of currying, if not just add your comment here ;)

Ruby and Functional Programming

 May, 24 - 2009   10 comments   Functional ProgrammingRuby

Ruby is known to support the functional paradigm. This article is going to walk you through the Functional Programming page on WikiPedia, to revise the general concepts of functional programming and to explain how Ruby supports them.
According to wikipedia, a functional programming can be described as follows:

In computer science, functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids state and mutable data. It emphasizes the application of functions, in contrast to the imperative programming style, which emphasizes changes in state. Functional programming has its roots in the lambda calculus, a formal system developed in the 1930s to investigate function definition, function application, and recursion. Many functional programming languages can be viewed as embellishments to the lambda calculus.

That’s a clear definition, however and if it’s not, the following walk through some concepts of functional programming should result in a better understanding:

Pure functions

In practice, the difference between a mathematical function and the notion of a “function” used in imperative programming is that imperative functions can have side effects, changing the value of already calculated computations. Because of this they lack referential transparency, i.e. the same language expression can result in different values at different times depending on the state of the executing program. Conversely, in functional code, the output value of a function depends only on the arguments that are input to the function, so calling a function f twice with the same value for an argument x will produce the same result f(x) both times. Eliminating side-effects can make it much easier to understand and predict the behavior of a program, which is one of the key motivations for the development of functional programming.

Pure functions support the mathematical definition of a function:

y = f(x)

Which means:
1- A function should return the same exact value given the same exact input.
2- A function does one thing exactly(has one clear mission), it has no side effects like changing some other value or write to stream or any other mission rather than its assigned one.

In fact Ruby doesn’t force you to write pure functions, but certainly it helps you to do so. Actually exercising yourself to write in pure functional style when possible helps you really in many ways:
1- It makes your code clean, readable and self-documenting.
2- It makes your code more “thread safe”
3- It helps you more when it comes to TDD.

Let’s have a look on how Ruby helps you do Pure functional code:

The ! symbol

Most of Ruby programmers know the ! symbol that comes at the end of method names like gsub!, merge! and many other methods. The ! symbol means: “Use it cautiously”. However If you focus more, you will notice that most of time, the ! symbol means: “This is a method that has a side effect; it alters the object which is invoked on!”.

As you can see, the upcase! method is not a pure functional method cause it has a side effect, it changes the string itself. On the other hand, the upcase method is a pure functional one as it returns the corresponding value with no other side effects.

On all hows, it’s highly recommended that you stick to this convention of method naming when you code in Ruby.


Everything is evaluated as an expression in Ruby: literals, method calls, variables… even a control structure has a value. For example you can do this in Ruby:

But that is a weak use of Ruby’s power, instead you’d better do:

Return value

Ruby returns the last expression value as the return value of the method invocation, so you don’t need an explicit return statement.

Together, the auto returned value and evaluating code as expressions are indeed a big support for pure functional code as finally they both serve the fact of having a value out of your method.

Higher-order functions

Functions are higher-order when they can take other functions as arguments, and return them as results. This is done in Ruby using lambda and block logic. If you don’t know how to use blocks, please do yourself a favor and visit this comprehensive article by Robert Sosinski.

Blocks in Ruby can help you do very nice things, one of them is ability to add control structure like syntax to your code. Check the following example, where a loop control structure is being defined:

Internal DSLs is also one of the nice things that you can achieve with block syntax in Ruby.

Currying and Partial Functions

Higher-order functions enable Currying, which the ability to take a function that accepts n parameters and turns it into a composition of n functions each of them take 1 parameter. A direct use of currying is the Partial Functions where if you have a function that accepts n parameters then you can generate from it one of more functions with some parameter values already filled in. Ruby 1.9 comes with support for this concept. check the following example:

For extended example about currying, check Ruby Currying blog post by me ;) .

Type systems and pattern matching

Pattern matching allows complicated control decisions based on data structure to be expressed in a concise manner. in simpler words, it’s a data structure based matching. Pure functional languages should support this concept, however and afaik this is still not supported in Ruby, but there are several trials to add this concept. check this blog post by Eric Torreborre.

Strict versus lazy evaluation

Strict evaluation always fully evaluates function arguments before invoking the function. Lazy evaluation does not evaluate function arguments unless their values are required to be evaluated. One use of Lazy evaluation is the performance increases due to avoiding unnecessary calculations.

However as the following example shows, Ruby use Strict evaluation strategy:

The third parameter of the passed array contains a division by zero operation and as Ruby is doing strict evaluation, the above snippet of code will raise an exception.


Iteration (looping) in functional languages is usually accomplished via recursion. Ruby doesn’t force you to recursion but it allows you to do so. However following recursion style has it’s own tax: Performance.
Ruby 1.9 comes with some “tail call optimizations”, more here.


1- As you can tell, Ruby helps you write in functional style but it doesn’t force you to it.
2- Writing in functional style enhances your code and makes it more self documented. Actually it will make it more thread-safe also.
3- The main support for FB in ruby comes from the use of blocks and lambdas, also from the fact that everything is evaluated as an expression.
4- Ruby still lack an important aspect of FP: Pattern Matching and Lazy Evaluation.
5- There should be more work on tail recursion optimization, to encourage developers to use recursion.
6- Any other thoughts?

Delegation in Ruby

 Apr, 26 - 2009   7 comments   GrailsRuby

This is my first article in, it was published in issue 1, so basically I’m just republishing it here again.

“Separate changeable parts from others that remain the same” and “composition is preferred to inheritance” are 2 common design principles when you start designing in OOP world. However and while the first seems to be logical, a one might wonder why it’s preferable to use composition over inheritance, and that’s a logical question, lets answer it via an example:

Let’s suppose that we have a Robot that has a heat sensor, a one would write a very simple UML:

This design has several drawbacks:

1.There is a strong probability to have another type of robots that don’t have heat sensors(breaks the first design principle: separate changeable code from static one).
2.Whenever I want to modify anything related to the heat sensor, I have to change the robot class(breaks the first design principle).
3.Exposure of heat sensor methods to in Robot class.

Let’s enhance this class a bit:

Well, now this is an inheritance based design and it solves the first problem, but it’s still incapable to solve the other 2 problems related to the heat sensor. Let’s do another enhancement:

Now this is a typical design, based on composition rather than inheritance, where we could solve the above 3 problems, and moreover we gained a new thing: we can now abstract the HeatSensor for future uses.

Now what’s delegation?

Delegation is the process of delegating functionality to the contained parts.
If you look carefully at the previous figure, you will notice that the VolcanoRobot is still having the 3 methods that are related to the sensor, well those are a wrapper methods, they do nothing but to call the sensor corresponding ones, and that’s exactly what delegation is, just delegate functionality to the contained parts(delegates).
Delegation comes along with composition to provide a flexible neat solutions like the one we had above, and also it serves the principle “separate changeable code from static one” ,but that also comes with a tax: a need of wrapper methods, and extra time needed in processing because of the call of these wrapper methods.

Ruby and delegation

Now let’s have a code example:
We have a multi purpose Robot that has an arm and a heat sensor, the robot does several jobs, like packaging boxes, stacking them and measuring the heat.
we will use composition and delegation as follows:

As you can see, i have 3 wrapper methods(stack,package and measure_heat) in Robot class that are doing nothing but to call the contained objects corresponding methods.
This is really a nasty thing, specially when there are lots of contained objects.
However there are 2 libs that comes to the rescue to in ruby, Forwardable and Delegate. Let’s check them one by one.

Forwardable lib

Forwardable lib is library that supports delegation, it has 2 modules Forwardable and SingleForwardable:

Forwardable module

The Forwardable module provides delegation of specified methods to a designated object, using the methods def_delegator and def_delegators.

def_delegator(obj, method, alias = method) : Defines a method method which delegates to obj. If alias is provided, it is used as the name for the delegate method.

def_delegators(obj, *methods): Shortcut for defining multiple delegator methods, but with no provision for using a different name.

Let’s refactor our robot example to make it Forwardable module:

Well, that’s a neater solution as you can see.

SingleForwardable module

The SingleForwardable module provides delegation of specified methods to a designated object, using the methods def_delegators. This module is similar to Forwardable, but it works on objects themselves, instead of their defining classes.

Delegate Lib

Delegate lib is another lib that provides delegation, i’ll explain 2 ways to use it:

DelegateClass method

Use the top level DelegateClass method which allows you to easily setup delegation through class inheritance. In the following example, I want to make a new class called CurrentDate, which holds the current date and some extra methods, at the same time I’m delegating to normal date objects:

SimpleDelegator class

Use it to delegate to an object that might be changed:

As you can see, we made 2 objects and then delegated to them consequently.

What about Rails?

Rails adds new functionality called “delegate”:
Which provides a delegate class method to easily expose contained objects’ methods as your own. Pass one or more methods (specified as symbols or strings) and the name of the target object as the final :to option (also a symbol or string). At least one method and the :to option are required.

go to your console and create a dummy project ,then cd to that project, and fire the rails console:

I strongly urge you to check the whole provided examples in rails API documetation,to check also how to use this effectively with ActiveRecord.

Before I finish this article I want to share you the code of delegate method form rails API documentation, I’ll add some comments on the code to explain you what is going on:

That’s it for this article, we have covered 5 points:

1-Composition vs inheritance.
2-What delegation is, and why it’s used.
3-Ruby Forwardable lib.
4-Ruby Delegate lib.
5-Rails delegate method.

C++ passes by reference, Java and Ruby don’t

 Apr, 22 - 2009   143 comments   C++JavaRuby

I got a lot of comments for the previous article, that was explaining how Ruby passes by value, just like Java does.

I thought that showing a simple example implemented in C++, Java and Ruby will clarify the idea. In the following lines, we will make swap functionality in 3 languages, and demonstrate that neither Java nor Ruby passes by reference.







As you can notice, in c++ example, passing by reference, will do the swap successfully.
Java and Ruby both don’t pass by reference, instead they pass a copy of the reference, which is a value finally, and so the swap fails, as swapping the copies doesn’t swap the original passed objects.

Please note also that in Java, primitive types are passed by their values directly and no need for any kind of references copies.The same case applies for Ruby, with immediate types(int, char…).

According to the previous 2 facts, we conclude that neither Java nor Ruby passes by reference, instead, both pass by value.

I think that fact that Ruby MRI is using C means they can’t use references, and so they are using pointers, and that explains why swap fails.

I hope that the idea is clear now.

Ruby, pass by value or by reference?

 Apr, 21 - 2009   38 comments   Ruby

It’s a basic question that I myself had a problem with when i started using Ruby: Does Ruby pass by value or by reference?
Well, if you want a direct answer, then: Ruby passes by value. It’s a similar behavior of what Java does.

Let’s prove it via examples:
Update: this example was passing integers, and it turned out that even everything in ruby is an object, but immedaite values are passed directly by their values, so i changed this example to let it pass strings instead.

Let’s pass an argument to a method and check what goes on:

As you see, we defined a method ‘change’ that takes a parameter ‘x’, changes it value and then returns it back. Then we invoked that method on the argument ‘y’ which had the value ’3′, and kept having the same value after the method invocation.
This simple example proves that the argument is not passed by reference, otherwise the value of ‘y’ would rather changed to ’10′ after the method invocation.

Now let’s take another example:

In this example, the passed argument value ‘hello’ has changed to ‘fello’, and thus it proves that the argument is not passed by value, otherwise the value of ‘s’ would kept having the same value ‘hello’.

Thus it’s not by value, neither by reference, then what is it?

As you know, everything in Ruby is an object, and thus, doing:

means: assign a reference(a place in memory that points to referenced value. In other words, it’s a place that holds the memory address of the referenced value) of the string ‘somthin’ to the variable named ‘val’, and normally when working with the variable ‘val’, it means we are working on it’s referenced object ‘smthing’.

But when invoking a method:

Things change a bit, as Ruby passes a copy of the ‘val’ reference itself(which is the memory address of the referenced object), not it’s referenced object, to the method Foo, and that copy will still reference the same object ‘smthing’ as the variable ‘val’ does.
This is called: Pass by Value, a copy of a reference to an object is passed, and so, not the referenced object itself is passed, neither the argument itself.
Then Ruby passes by value. Some ppl like to call it “pass by reference value”, but that’s not standard afaik.

That explains what goes in both examples, as in the first example the value of the argument ‘y’ didn’t change due to the fact that we are not passing the reference ‘y’ itself, instead a copy of it, and thus, when its copy referenced another object(via assignment operator), the original variable ‘y’ kept referencing it’s object, the object with value ’3′ in our case. As for the second example, the argument ‘s’ changed due to the fact that its passed copy is still referencing the same object ‘hello’, but the operator [] changed the referenced object value, and thus got a new value ‘fello’.

I hope the idea is clear now, if not, please don’t hesitate to comment.

I have blogged a new article explaining passing by reference and value in 3 languages c++, java and ruby

The power of JRuby

 Jan, 11 - 2009   31 comments   JavaJRubyRuby

It’s true that I’m not the qualified guy to talk about Java’s power,as it has been 2 years since i last practiced it, but i feel like i have to communicate my thoughts to the people that didn’t give JRuby a trial yet, and why they should do so.
If you never worked with Java before, then don’t panic, cause in these article i would list several reasons why JRuby is so powerful even if you don’t know anything about Java.
Lemme start listing all the points that makes me feel the power of JRuby; the order here is irrelevant as i do believe that every point listed bellow has somehow the same rank that others might have:

1- Mixing the power of Java with the power of Ruby.
2- A faster(if not the fastest) Ruby implementation.
3- Native Threads.
4- Support for Foreign Function Interface(FFI).
5- Make use of the JVM (HotSpot).
6- Have a great community and support.

Mixing the power of Java with the power of Ruby

There are thousands of Java packages that are ready for you to use, and according to TIOBE, Java is continuing to be the most popular language, so why don’t you make use of the existing Java packages, and use them inside your code?
For example, you can use the swing package(a very powerful GUI package) inside your ruby code, the following snippet of code is taken from the samples folder in the JRuby distribution:

You can also reference ruby code inside Java code, examples could be found here.

A faster(if not the fastest) Ruby implementation

JRuby team consider it a bug if they are slower on something than MRI, thus they keep enhancing the performance of JRuby.
According to Antonio Cangiano, the guy behind the great ruby shootout here and here:

Ruby 1.9 and JRuby are very close, respectively 2.5 and 1.9 faster than Ruby 1.8.7 (from source) on these benchmarks.

Surprisingly JRuby was slower than ruby 1.8.6 last year, but now it’s competeing 1.9 in terms of speed.
Charles Nutter the JRuby team leader commented on that saying:

I’m looking forward to seeing another update once JRuby finishes 1.9 support, since these JRuby numbers don’t reflect execution and library optimizations 1.9 provides. I expect that JRuby in 1.9 mode will perform much closer to Ruby 1.9.

Until then, it’s good to hear we’re the fastest 1.8 implementation. Thanks again!

Native Threads

The current ruby interpreter which is called MRI supports green threads, as opposed to JRuby which supports native threads.
Green threads are managed by VM, not by the operating system, and thus, by using them you lose a significant power called “concurrency” which is available to multi core processors, that’s because the VM will continue to use one core to serve the whole threads, as opposed to native threads which will use the full power of multi core processor, by being assigned to the available cores.
In general an application might be IO-bounded(lots of IO operations, like logging and database related ones) or CPU-bounded(lots of computation), and while green threads are useful for the IO-bounded applications, they are not useful for the CPU-bounded ones.
A CPU-bonded applications consumes the CPU, and thus you can increase the speed of your program by having multi core processor, but thus you need native threaded applications, to make use of the available cores.
JRuby comes to rescue as it supports native threads, and thus you have full concurrency when you have multi core processors.

Support for Foreign Function Interface(FFI)

According to wikipedia a Foreign Function Interface (or FFI) is :

A mechanism by which a program written in one programming language can call routines or make use of services written in another.

Why would a one need that? well many gems that we use like Rmagic,Hpricot and ruby-prof uses C extensions, either because of performance or because of the ready existing libs related matters.
Well that was causing problems for JRuby users as they couldn’t run those gems that have C extensions, and also for gem developers who had to maintain 2 versions of such gems to let them work for both MRI and JRuby.
That was a kind of disaster till Charles announced that FFI is available for ruby.
So now when you need to have C code inside ruby, then it’s highly recommended to use the FFI gem to save yourself having dual code, and also to make your code work on different ruby implementations.

Make use of the JVM (HotSpot)

Since Sun has announced it’s open source strategy, and lots of optimization work was done for the JVM(HotSpot), the reason behind these optimizations was the fact that many languages is adopting Java to be the hosting language for them, and thus having JVM as an open source technology helped to optimize it to better serve these languages. Some of these languages are: JRuby, Groovy, Scala and Clojure.
So you might be wondering “How this will affect me?”, actually it will affect you indirectly cause once you have a better JVM, it means you have a faster JRuby implementation, and a better management for your memory, as the JVM is considered to have the best garbage collector.
Also you might be able one day to work with other languages(Clojure for example) directly in your ruby code.

Have a great community and support

JRuby has a very nice community, and the guys behind it are very helpful and open to different opinions, just log to #JRuby channel on the FreeNode on IRC, or subscribe to mailing list and send your questions, and you will get the minimum support to let you go.
What i like about this community is their love to the Ruby community, they like to help any rubiest, they even worked with Merb(merb 2 is the core of Rails 3) guys to provide a better performance for merb users.
The current active JRuby contributers are: Charles Nutter, Tom Enebo, Wayne Meissner, Marcin Mielzynski and Nick Sieger, and here some of the past contributers: Ola Bini and Vladimir Sizikov

I hope that i could deliver some of the good points about JRuby, and would like really to have your comments, and what might be also missing from those points. You can find bellow a list of references.


*JRuby: What, Why, How…Try It Now by Charles Nutter and Tom Enebo

*JRuby: The Pain of Bringing an Off-Platform Dynamic Language to the JVM by Charles Nutter

*Charles Nutter blog

Update 1
The snippet of code was updated as a respond to Collin’s note