Google App Engine, JRuby, Sinatra and some fun!

 Mar, 06 - 2011   24 comments   GAEJRubyRubySinatra

Yesterday I was experimenting with Google App Engine for a little project that I was working on. I literally started from ground zero and could do my thing after a long night. I’m blogging about it to share you the idea and save you some time googling solutions. So, here is the thing in brief: I wanted to parse some feed on periodical basis and send an email with new entries.

Looks like a 10 minutes with Nokogiri and cron jobs. Actually that’s true except of the fact that I need to pay for a VPS so that I can run the script with various gems (since I needed to do some work on the feeds before sending, but that’s for another topic) and for using cron jobs. Thus, I decided to try something new this time and I went with GAE since it has memecached that I can use as an LRU cache, also it has cronjobs and finally it has a mail system. I’m using JRuby and Sinatra for this project.

Here are the steps:

Install JRuby, I’m using RVM on my machine:

Install needed gems, those versions are the ones which worked for me:

Create a simple app:

Now let’s create the following files (Please note that the following code can be further enhanced):

Gemfile

config.ru

(fill the sender/receiver emails and the feed URL)

app.rb

cron.xml

(You can set the period here, I’m using 15 minutes intervals)

Now, create an application-id at appspot.com. Then go to Administration >> Permissions and make sure the sender/receiver emails play some role in the app. Personally, I granted them the developer role.

Now, go back to the source and modify the application-id in WEB-INF/app.yaml

We should be ready now, start development server, watch the console and make sure no exceptions are there:

If everything is OK, go to http://localhost:8080/notfiy and you should see “Done”.

Let’s go live now:

(the first time you execute this, you will prompted to submit the GAE email/pass combination)

It should now be running at http://your-app-id.appspot.com, and in few minutes you should be receiving the first email. If not, go to app engine page then to Main >> Logs and check what’s the problem.

I like this stack cause it’s Zero cent cost, Zero deployment time, flexible, and it gives me exactly the freedom I want in terms of needed gems. Give it a shot, you won’t regret it!


StackOverflow cool Ruby questions 4

 Mar, 16 - 2010   8 comments   RubyStackoverflow

Welcome to the fourth post of this series. Just before proceeding to the questions, I would like to mention the great Metaprogramming Ruby: Program Like the Ruby Pros book by Paolo Perrotta, a very good book that explains the metaprogramming aspects of the Ruby language.
Now let’s get going!

Scope gates

Taken from the above mentioned book:

There are exactly three places where a program leaves the previous scope behind and opens a new one:
• Class definitions • Module definitions • Methods
Scope changes whenever the program enters (or exits) a class or module definition or a method. These three borders are marked by the keywords class, module, and def, respectively. Each of these keywords acts like a Scope Gate.

The question title is: Closure doesn’t work

The question text is:
If block is a closure, why this code does not work? And how to make it work?

The answer is:
Blocks are closures and arg is indeed available inside the Class.new block. It’s just not available inside the foo method because def starts a new scope. If you replace def with define_method, which takes a block, you’ll see the result you want:

Almost everything in Ruby is an object

The question title is: Examples of ‘Things’ that are not Objects in Ruby

The question text is:
“Everything is an object” was one of the first things I learned about Ruby, but in Peter Cooper’s Beginning Ruby: From Novice to Professional book, it is mentioned that “almost everything in Ruby is an object”.

Can you give me some examples of things that are not objects in Ruby?

The answer is:
he most obvious one that jumps into my head would be blocks. Blocks can be easily reified to a Proc object, either by using the &block parameter form in a parameter list or by using lambda, proc, Proc.new or (in Ruby 1.9) the “stabby lambda” syntax. But on its own, they aren’t objects.

Another example are built in operators: while methods are objects, some operators are not implemented as methods (and, or &&, ||), so those operators aren’t objects.

Hash keys

The idea here is that whenever you want to define your own keys types for Ruby hashes, then you need to define 2 methods #eq? and #hash for those types.

The question title is: How to make object instance a hash key in Ruby?

The question text is:
I have a class Foo with a few member variables. When all values in two instances of the class are equal I want the objects to be ‘equal’. I’d then like these objects to be keys in my hash. When I currently try this, the hash treats each instance as unequal.

f1 and f2 should be equal at this point.

should print 8

The answer is:
See http://ruby-doc.org/core/classes/Hash.html

Hash uses key.eql? to test keys for equality. If you need to use instances of your own classes as keys in a Hash, it is recommended that you define both the eql? and hash methods. The hash method must have the property that a.eql?(b) implies a.hash == b.hash.

The eql? method is easy to implement: return true if all member variables are the same. For the hash method, use [@data1, @data2].hash

Kernel#abort

The question title is: Ruby – Exit Message

The question text is:
Is there a one line function call that quits the program and displays a message? I know in Perl its as simple as this:

Essentially I’m just tired of typing this:

The answer is:
The ‘abort’ function does this. For example:


StackOverflow cool Ruby questions 3

 Jan, 29 - 2010   6 comments   RubyStackoverflow

Welcome to the third post of this series. Just before diving into the new questions’ set, I want to mention a little script that I wrote to notify the user when a new question is posted on Stackoverflow, it works on Mac and uses growl.
Now let’s proceed to questions:

Relationship between the metaclass of base and derived classes

The question title is: What is the relationship between the metaclass of Base and Derived class in Ruby?

The question text is:

In Ruby, we could use super within singleton method to call the corresponding super class’s singleton method, like the following code shows.

However, I don’t seem quite get how that call to super within Derived.class_method could reach Base.class_method. I’d assume that class_method is defined on their metaclass, does that mean their metaclass has parent/child relationship? (I can’t quite confirm that by experiments)

I’m asking this question because I remembered seeing somewhere there’s some kind of relationship between base and derived class’ metaclass (but I can’t find it any more). In addition to know how actually super works, I’d also like to confirm whether the two metaclasses are totally separate or not.

The answer is:
There are four class objects in play here:

Nomenclature:

  • <...> is the class of each object.
  • The name of the class is on the second line.
  • If the name starts with #, it’s the eigenclass (aka singleton class).
  • super points to a class’s superclass
  • class points to the class’s class.

When you call Derived.class_method, Ruby follows the “right one and then up” rule: First go to the object’s class, then follow the superclass chain up, stopping when the method is found:

  • The receiver of the “class_method” call is Derived. So follow the chain right to Derived’s class object, which is its eigenclass (#Derived).
  • #Derived does not define the method, so Ruby follows the chain up the chain to #Derived’s superclass, which is #Base.
  • The method is found there, so Ruby dispatches the message to #Base.class_method

You don’t think I knew all this stuff off the top of my head, did you? Here’s where my brain got all this meta juju: Metaprogramming Ruby.

Part 2. How to make an “eigenclass” (aka “singleton class”) come out of hiding

This method will return the eigenclass of any object. Now, what about classes? Those are objects, too.

Note: Above is from Ruby1.9. When run under Ruby 1.8, you get a surprise:

Idiomatic object creation

The question title is: Idiomatic object creation in ruby

The question text is:

In ruby, I often find myself writing the following:

or even

I’m always keen to minimize boilerplate as much as possible – so is there a more idiomatic way of creating objects in ruby?

The answer is:

Struct objects are classes which do almost what you want. The only difference is, the initialize method has nil as default value for all it’s arguments. You use it like this

or

Struct has one big drawback. You can not inherit from another class.

Block vs brackets

The question title is: Using do block vs brackets {}

The question text is:

New to ruby, put on your newbie gloves.

Is there any difference (obscure or practical) between the following two snippets?

I realize the bracket syntax would allow you to place the block on one line

but outside of that are there any compelling reasons to use one syntax over the other?

The answer is:

Ruby cookbook says bracket syntax has higher precedence order than do..end
Keep in mind that the bracket syntax has a higher precedence than the do..end syntax. Consider the following two snippets of code:

Second example only works when parentheses is used, 1.upto(3) { |x| puts x }

String and whitespace

The question title is: See if a ruby string has whitespace in it

The question text is:

I want to see if a string has any white space in it. What’s the most effective way of doing this in ruby?

Thanks

The answer is:

If by “white space” you mean in the Regular Expression sense, which is any of space character, tab, newline, carriage return or (I think) form-feed, then any of the answers provided will work:

Index of the largest value in an array

The question title is: In Ruby, what is the cleanest way of obtaining the index of the largest value in an array?

The question text is:

If a is the array, I want a.index(a.max), but something more Ruby-like. It should be obvious, but I’m having trouble finding the answer at so and elsewhere. Obviously, I am new to Ruby.

The answer is:

For Ruby 1.8.7 or above:

It does one iteration. Not entirely the most semantic thing ever, but if you find yourself doing this a lot, I would wrap it in an index_of_max method anyway.

each_with_index without a block returns an enumerator that gives the item and its index. We then send max to this enumerator, which does the standard max algorithm on item-index pairs. Array.<=> is implemented so that the first item determines the ordering (unless there’s a tie, in which case the second is compared, and so on), so this works basically the same as doing max on an array of the values themselves. Then to get the index, we ask for the second item of the result (since we got a series of [value, index] pairs from each_with_index)


StackOverflow cool Ruby questions 2

 Oct, 17 - 2009   8 comments   RubyStackoverflow

Welcome in this second post of this series. Just before I list the questions of this one, I want to mention 2 things:

  • You can follow StackOverflow tagged Ruby questions on twitter using the user: sof_ruby
  • Some ppl feel shy to ask or even to answer, my (little) experience in life taught me that If you don’t ask, you don’t learn. If you don’t participate, you don’t learn. On the other side that’s the benefit of pair programming, ain’t it?

Now let’s proceed to questions:

Hash Autovivification

Hash Autovivication in simple words is the ability to do things like:

The cool idea here is that all intermediate-level hashs will be created automatically.
We can’t do that directly in Ruby, a statement like the previous one will issue an error : NoMethodError: undefined method `[]' for nil:NilClass

The question title is: ruby hash autovivification (facets)

The question text is:
Here is a clever trick to enable hash autovivification in ruby (taken from facets):

Although it works (of course), I find it really frustrating that I can’t figure out how this two liner does what it does.

The answer is:
The standard new method for Hash accepts a block. This block is called in the event of trying to access a key in the Hash which does not exist. The block is passed the Hash itself and the key that was requested (the two parameters) and should return the value that should be returned for the requested key.

You will notice that the leet lambda does 2 things. It returns a new Hash with leet itself as the block for handling defaults. This is the behaviour which allows autonew to work for Hashes of arbitrary depth. It also assigns this new Hash to hsh[key] so that next time you request the same key you will get the existing Hash rather than a new one being created.

So:

Class instance variables

This answer of this one is easy, but the idea of Class instance variables is what matters.

The question title is: Total newbie: Instance variables in ruby?

The question text is:
Pardon the total newbiew question but why is @game_score always nil?

The answer is:
Because you don’t have

The assignment in the class definition is not doing what you think it is doing, and when hit gets invoked it can’t add to nil.
If you now ask what happened to @game_score?, well, always remember Class is an object and Object is a class.
It’s way cool the way Ruby classes have this Zen-like “real” existence. Ruby doesn’t precisely have named classes, rather, class names are references to objects of class Class. By assigning to @game_score outside of an instance method you created a class instance variable, an attribute of the class object Bowling, which is an instance of class Class. These objects are not, in general, very useful. (See Chapter 1, The Ruby Way, Hal Fulton.)

You can reach the @game_score class instance variable by doing this:

(A question for you: What is the difference between class variables and class instance variables?)

Creating data structures in Ruby

I have committed a mistake myself in answering this question :P, however remember: If you don’t try, you don’t learn.

The question title is: Can the array be reinvented in Ruby?

The question text is:
This is just a hypothetical question, if you wouldn’t have the Array and the Hash class, would there be any way of implementing an Array class in pure Ruby? How?

The answer is:
Yes we can:

This works by creating instance variables @a0, @a1, etc. on the object to represent array indices 0, 1, etc. It has constant time length and index operations. The rest of the operations (remove, etc.) are a bit more effort to implement, but it’s absolutely possible.

Note that the constant time property for the index operation depends on the underlying Ruby runtime using an appropriate data structure for instance variables.

Hash#reject

The question title is: Update attributes unless blank?

The question text is:
I have an existing Project record, and I’m importing a CSV file to update the associated Project attributes. However, often the CSV will contain blank fields and I don’t want to overright exisiting attributes if the related CSV field is blank.

Something like this:

The answer is:

Ruby ‘private’ behavior

The key point here to remember is that private, protected and pulbic are just other methods defined in Ruby Module class.

The question title is: Are there good reasons for ‘private’ to work the way it does in Ruby?

The question text is:
It took me a while to understand how private methods work in Ruby, and it really strikes me as being very awkward. Does anyone know if there are good reasons for private methods to be handled the way they are? Is it just historic reasons? Or implementation reasons? Or are there good solid logical reasons (ie. semantic)?

For example:

  • Ruby’s behaviour on lines (1), (2) and (5) seems reasonable.
  • The fact that (6) is ok is a bit strange, especially coming from Java and C++. Any good reason for this?
  • I really do not understand why (3) fails ! An explanation, anyone?
  • The problem on line (4) looks like an ambiguity in the grammar, which has nothing to do with ‘private’.
  • Any ideas?

The answer is:

You might find it helpful to read ruby’s definition of public, private and protected (Skip to Access Control)

Ruby’s private is analogous to Java’s protected. There is no Ruby equivalent of Java’s private. But there are ways to fake it.

Private is defined as methods/variables that can only be called implicitly. This is why statements 2 and 3 fail. In other words, private limits methods/variables to the context of a class or subclass in which they are defined. Inheritance passes private methods to the subclasses and can therefore be accessed with an implicit self. (Explaining why statement 6 works.)

I think you’re looking for something closer to protected. Which behaves similarly to Java accessors that are not given a visibility (eg: public, private, protected) By changing the private in Spy to protected all 6 of your statements work. Protected methods can be called by any instance of the defining class or their subclasses. Either explicitly or implicitly called on self are valid statements for protected methods so long as the caller is either the class of the object responding to the call, or inherits from it.

As for statement 4. You are correct in assuming this is to avoid ambiguity. It’s more a safeguard to the potential harm of ruby’s dynamic nature. It ensures that you cannot override accessors by opening up the class again later. A situation that can arise, for example by eval’ing tainted code.

I can only speculate on he design decisions that led to these behaviours. For most of it I feel it comes down to the dynamic nature of the language.

P.S. If you really want to give things the java definition of private. Only available to the class in which it’s defined, not even subclasses. You could add an self.inherited method to your classes to remove references to the methods you want to limit access to.

Making the weight attribute inaccessible from subclasses:

It may make more sense to replace the undef_method call to something like this:

Which provides a much more helpful error and the same functionality.

The send is necessary to get around calling private methods for other classes. Only used to prove that things are actually working.

Which in hindsight, makes private and protected useless. If you’re really serious about protecting your methods you will have to override send to block them. You could also make send private.

It ends up being one of those “Damned if you do, damned if you don’t” situations. There are legitimate uses of calling send from outside an object. And overriding send requires some tricky code to account for the variable number of arguments that can be sent to any method.

That’s an exercise for another time.

Suggestions/comments regarding the content of this series are welcome! Have your say!


StackOverflow cool Ruby questions

 Sep, 29 - 2009   10 comments   RubyStackoverflow

I have participated heavily during the last 2 weeks in answering Ruby tagged questions on stackoverflow. That took place mainly after Ryan Bates tweet wishing to see more Ruby developers on stackoverflow. Since then I have enjoyed reading various kinds of questions that range in level from basic to professional ones and which cover various stuff like normal questions, tricks, meta programming, best practices and language specific features.

So, I’m announcing in this post an endless series called “Stackoverflow cool Ruby questions” which will target cool Ruby questions on stackoverflow. I strongly recommend that you visit Stackoverflow on daily basis and try to participate if you have the time, but if you don’t, then I hope that you will enjoy this educational series.

There are currently more than 4,640 tagged Ruby questions, I’ll try to mix old + recent questions. I won’t cover basic questions here unless the question gets high votes. The covered questions will be related to new, tricky and controversial topics.

Please don’t hesitate to give any notes regarding the idea and the way the questions are picked and presented.

Let’s start this series, with 3 questions for this post:

‘Instance_eval’ instead of ‘yield(self)’

The question title is: Instance Eval Within Block

The question text is:

Now, how do I change this

Into this?

The answer is:

The trick here is to use instance_eval which evaluates the passed block in the context of the current object called on.

Determining whether a variable is any one of a list of values

The question title is: Shortest/most idiomatic way of determining whether a variable is any one of a list of values

The question text is:

This seems a ridiculously simple question to be asking, but what’s the shortest/most idiomatic way of rewriting this in Ruby?

I’ve previously seen this solution:

but this isn’t always functionally equivalent – I believe Array#include? actually looks to see if the variable object is contained in the list; it doesn’t take into account that the object may implement its own equality test with def ==(other).

Take, for example, Rails’ Mime::Type implementation: request.format == :html may return true, but [:html].include?(request.format) will return false, as request.format is an instance of Mime::Type, not a symbol.

The answer:
Actually, #include? does use ==. The problem arises from the fact that if you do [:a].include? foo, it checks :a == foo, not foo == :a. That is, it uses the == method defined on the objects in the Array, not the variable. Therefore you can use it so long as you make sure the objects in the array have a proper == method.

In cases where that won’t work, you can simplify your statement by removing the select statement and passing the block directly to any:

Using ‘instance_eval’ instead of ‘send’

The question title is: How to evaluate multiple methods per send command?

The question text is:

Let’s say I have an XML::Element…I want to do something like:

The answer is:

In your case it’s better to use instance_eval

And for your code:


Observer and Singleton design patterns in Ruby

 Aug, 21 - 2009   13 comments   Design PatternsRuby

This is my first article in http://railsmagazine.com, 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
class.
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!


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 block.call(*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.

Expressions

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.

Recursion

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.

Conclusion

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 http://railsmagazine.com, 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.



OLDER POSTS