Archive for the 'Ruby' Category

Module and Mixin revisited

From the feedback I got from ruby on rails course, there seem to be many students who find many core concept of ruby difficult to understand. So, the course mailing thread aside, I’ll try my best to explain some of these concept in depth here. This post will be about the concept of Mixin and ruby Module.

Mixin and Module

Wikipedia offers one of the best description of what mixin is.

In OO languages, a mixin is a  class that provides a certain functionality to be inherited by a subclass, but is not meant to stand alone. Inheriting from a mixin is not a form of specialization but is rather a means to collect functionality. A class may inherit most or all of its functionality by inheriting from one or more mixins through multiple inheritance.” - Wikipedia

Ruby’s flavor of mixin comes in the form of Module. Module is a collection of methods and constant. The most commonly use of module is to have its members (methods, features) “mixed” into a class. The most evident example is the Kernel methods that are mixed-in to Object class. Because of this, methods from Kernels are universally available to all ruby objects.

Basic example

In the last post, I showed an example of ‘puts’ method. ‘puts’ is available to all Object in Ruby. ‘puts’ exists in Kernel module, and Kernel is mixed into Object class. Now since everything in ruby is an Object, they also automatically have access to ‘puts’ in Kernel module.

puts "string".class.ancestors
# [String,Enumerable,Comparable,Object,Kernel]

puts Object.class.ancestors
# [Class,Module,Object,Kernel]

puts Object.private_methods.include?('puts')
# true => Object has 'puts' method as member

puts Object.class.private_methods(false).include?('puts')
# false => 'puts' is inherited member

puts Kernel.class.private_methods.include?('puts')
# true => 'puts' is a member of Kernel module

Another example is the use of Math module. you can access Math’s constant value without having to include Math module

puts Math::PI
# 3.141592653589793

puts Math.sqrt(256)
# 16

Matz has called the mix-in feature of module “single inheritance with implementation sharing“. It’s a way of getting benefit of multiple inheritance without the mess and difficulties.

Module instance method

With “include” keyword, the modules methods become available  as object’s instance methods. You can think of including Ruby module to a class is similar to appending functions of that module to an object.

module MyModule
   def instance_method
      puts 'this is MyModule instance_method'
   end
end
class MyClass
   include MyModule
end
my_class = MyClass.new
my_class.instance_method #this is MyModule instance_method

As you can see, with ‘include‘ keyword, MyModule’s method becomes available to all instance of MyClass object.

Module class method with append_features

It’s also possible to make module methods available to class. What we’re going to use is ‘append_features‘. By overriding module’s ‘append_features' method with class as parameter, nested method under append_features will be accessible to that class.

module MyModule
   def MyModule.append_features(childClass)
      def childClass.classMethod
         puts 'MyModule classMethod'
      end
      super #HAVE to call super here
   end
 
   def instance_method
      puts 'this is MyModule instance_method'
   end
end
my_class = MyClass.new
my_class.classMethod     # illegal
MyClass.classMethod      # print MyModule classMethod

A few things to note here. First,’append_features‘ actually do the work equivalent to include operation. Therefore, we need to call super. Otherwise, the rest of the code in the module wouldn’t be included at all. Another thing, the nested method can only be singleton/static method.

Module class method with inheritance

Alternative to using append_features, you can mix in module’s instance methods as class methods with inheritance

class MyOtherClass
   class << self
      include MyModule
   end
end
MyOtherClass.instance_method
# print this is MyModule instance_method
# instance_method becomes class method

As you can see, the ruby language itself is very powerful. But by nature, it still follows the Object Oriented principle. On the future post, I’ll review the concept of blocks and lambda expression.

No Comments »

Teera on July 29th 2008 in Software Development, Ruby

Everything is an object (in ruby).

Less than a week since it began, many interesting discussions have been floating around ruby on rails course mailing thread. A great one in particular is the discussion on the OO-ness of ruby taken from the conversation between Victoria Pocladova and Raul Parolari. Consider this:

“Ruby is an object oriented language and an object has a well-defined interface that specifies the behavior of the object in a manner that is independent of its implementation. This interface defines the collection of services that can be invoked by other objects.” - http://c2.com/cgi/wiki?ObjectOriented

Main.rb and Object

The next questions become how would you describe the behavior “main.rb”? You can have blocks of code within the main class, and no method containing this code. How is this code exactly invoked by another objects, or by the compiler itself when the main class is executed? And since I don’t have any methods in the main class, where does the “puts” command come from? Does main class get special treatment like void main() method in Java?

It does seem a bit contradiction to the earlier paragraph describing the OO concept of ruby. Raul Parolari, my course adviser colleague, offers a great explanation of this.

First, let’s try creating a main.rb file and execute this line of code.

puts self #main
puts self.class #Object

‘main’ is like the backstop of Ruby program. It is the farthest back you can fall; but it is also the current object as soon as your programs starts up. By the way, ‘puts’ is in Object? no, it is a method of module Kernel. But wait a moment; didn’t we say that ’self’ class was Object? how can we call ‘puts’ on an Object instance? Because… every object’s search path includes the Kernel module; and how is that?

Kernel module

That’s because the class Object mixes in Kernel, and every object’s Class has Object as an ancestor. Now try this

puts self.class.ancestors #[Object, Kernel]
puts 'string'.class.ancestors # [String, Enumerable, Comparable, Object, Kernel]

Again, we see Kernel lurking at the back.

puts

The next thing we can investigate is if ‘puts’ is actually a member of Object.

puts self.class.private_methods.include?('puts') #true
puts Object.private_methods.include?('puts') #true

Oh wait? Didn’t I just say that ‘puts’ is a method of module Kernel? If you trace EVERY class in ruby, you’ll see Object and Kernel at the top of inheritance hierarchy. Now let’s try to interogate Object class again and keep out inherited members.

puts Object.private_methods(false).include?('puts') # false
puts Kernel.class.private_methods.include?('puts') #true

Gotcha! As you can see, ‘puts’ is actually a member of Kernel module that Object benefits from. And since every class in ruby is an Object, they all benefit from the work of Kernel as well.

As the lead adviser for this program, I’m astound to see this kind of thing in the discussion thread myself. The understanding of core concept highlights beauty and benefits of the language.

1 Comment »

Teera on July 25th 2008 in Software Development, Ruby

Giving back to the community

I’ve recently been appointed as the lead adviser for JavaPassion.Com’s Ruby on Rails online training course by the legendary Sang Shin. I talked about this Ruby on Rails online course in my previous post. At the time of this writing, there are 998 registered students and will likely to hit 1K in a few hours. As the lead adviser, I’ll basically be the go-to guy for students when it comes to questions and assist Sang in developing course content.

I must say that I am no expert in RoR. I picked it up only about a year ago as a hobby. Since then my experience and relationship with Ruby and Rails communities have been nice and warm. The same goes for Java and other open source communities. Quite often that I think about giving back and contribute to open source projects. However, neither my coding skills nor my schedule had allowed me to do so. So my resolution becomes

If I can’t make a contribution in code, then I’ll do it in the form of content!”.

And here it goes… :)

Reminder: the course starts July 15th, go register if you havn’t done so!

2 Comments »

Teera on July 12th 2008 in Ruby, Personal

Learning Ruby on Rails with passion!

Sang Shin has started a new online training course on Ruby on Rails. This is a great learning opportunity for both beginners and experts. If you are interested in learning more about RoR and JRuby, make sure to check it out. The first session will start on July 15th.

For more detailed information on the course, please see the following
Course topics: http://www.javapassion.com/rubyonrails/#Topics
Course website: http://www.javapassion.com/rubyonrails

The course contents are still being worked on and will be updated as we move along. But some of the hands-on labs (including several real-life Rails applications you can build and run as Netbeans projects with minimum effort) are ready for your peruse.

If you have any questions or comments, feel free contact me or Sang directly. I’m involved in the development of this program as well.

1 Comment »

Teera on May 15th 2008 in Software Development, Ruby, Netbeans

Packaging open source Ruby on Rails app (Typo) as Netbeans project

For the past week I’ve started working with Sang Shin to convert some open source Ruby on Rails applications as Netbeans projects for download. So far the process has been fairly easy. My goal for this post is to show you how to pull down RoR project source code from source control (Subversion) and convert it to a Netbeans project.

Typo blogging engine

Project site: http://www.typosphere.org

Dev site: http://trac.typosphere.org

Checking out source code from Subversion

With Netbeans, working with Subversion can’t be any easier. First I fire up Netbeans 6.1, then on menu bar, choose ‘Versioning’ > ‘Subversion’ > ‘Check out’

Typo1

 

Netbeans will ask for repository URL and source revision number.

typo2.png

Next, enter the directory where you want the source files to go to. Note that I tick “Skip release_4_1_x and check out only its content”. This is because I do not want additional folder level. I want the source files to go directly to ‘Typo’ folder I’ve created earlier.

typo3.png

Lastly, Netbeans will ask if you want to create a new project for the source you just checked out.

typo4.png

Choose Ruby on Rails project with existing resource and navigate to the source folder.

typo5.png

The last step is to name your project and select version of ruby to run and web server.

typo6.png

And that’s all :) easy right? You can download Netbeans project for Typo HERE.

TextMate dark theme on Netbeans 6.1

I always like the cool dark theme Ruby/Rails editor in TextMate and now it’s available for Netbeans. Tor Norbye’s blog for detailed setup instruction HERE. This TextMate theme is not limited to RoR editor but it works with Java editor as well. Well worth check it out.

Netbeans dark theme for Ruby editor
TextMate style Ruby editor on Netbeans

Netbeans dark theme for Rails

Netbeans dark theme for Java
This theme also works with Java editor too! Neat!

Netbeans dark theme for XML editor
Dark theme for XML editor

No Comments »

Teera on March 26th 2008 in Software Development, Ruby, Netbeans, Java

Dynamic jar loading in JRuby Netbeans tutorial

Last month I got a feedback email from a developer on my earlier Netbeans tutorials. After successfully packaging JRuby desktop app in a jar, he had a problem with loading class from third party jar files locate outside the package.

The easiest solution was to package the third party jar file at two places: one inside the package for ruby script to access, another outside the jar package for Java class. But that wouldn’t be a good solution. After some thoughts and fiddling around, I came up with ruby script that can dynamically load a class and create class instance from external jar file. This way you only need to include one copy of the third party jar file outside the package.

I’ve created a Netbeans doc tips & tricks for this script, you can check it out here:

Netbeans Tips & Tricks: Dynamic Jar Loading in JRuby 

No Comments »

Teera on March 13th 2008 in Software Development, Ruby, Netbeans, Java

Netbeans 6 and Mac Java 6 Developer Preview 9 project wizard hangs problem

If you have downloaded and installed the recent release of Mac Java SE 6 Developer Preview 9, you might be experience a problem of Netbeans ‘New Project’ dialog hangs. The symptom could be varied, in my case, I could create new Java Web and Enterprise projects, but not Ruby or Java application projects. Once I clicked ‘Finish’ on Netbeans’ new project wizard dialog, the dialog would hang without new project being created.

Netbeans 6 on Mac new project wizard hangs with Java 6 Preview 9
This dialog hangs forever

This happens because AppleScriptEngine.jar bundled in Apple’s Java SE 6 Preview 9 package was originally compiled with JDK 6. Since the folder containing this file is shared across all installed JDK versions, the problem occurs.

The solution here is quite simple. Simply remove AppleScriptEngine.jar under /System/Library/Java/Extensions folder and Netbeans IDE will run fine.

2 Comments »

Teera on March 4th 2008 in Software Development, Ruby, Netbeans, Java

Bridging JRuby on Rails and Java with MVP

On my last post, I’ve explained how Model-View-Presenter (MVP) pattern and help you achieve extensibility on Java platform by decoupling your application from presentation technology. Yet, it’d be a shame if I stop the discussion there - I have not mentioned anything about the JVM! On this post, I’ll take it a step further. I’ll show you how you can leverage the power of Java Virtual Machine (JVM) and MVP pattern to transform your Java application to JRuby on Rails.

You can download the source code for this example HERE

Power of the JVM

Being on Java platform, developers can also reap another benefit from their best friend: the JVM. To demonstrate what good Java VM can bring is to look at this example. Assume that our bookstore site has become popular and our CEO just recently returned from a Ruby on Rails user group meeting. The CEO declares that we need to jump on the Rails bandwagon and get books data from XML file instead of hard coding it in the application.

The issue here is now we have to migrate our application across different technologies. To minimize cost and avoid writing a lot of code, we decide to leverage existing Java platform and go with JRuby.

JRuby allows Ruby class to implements Java interface. So we first start from creating a new data model where it reads books data from XML file.


Reading books data from XML file with REXML library


Sample XML books data

Rails controller = The ‘View’ controller

Now that we have the data model ready, we go ahead to implementing the view layer. This is similar to last example on servlet and JSP. We have Rails controller class implements the IBookDetailView interface. The controller is responsible for fetching data to .rhtml file to display.

The key idea here is that it’s the Rails controller that is the ‘View’ in MVP. The presenter is simply an instance of BookDetailPresenter Java class that we can use here with the magic of JRuby.

Rails controller implements IBookDetailView interface


Rails controller acts as the view and controls data that will get displayed on rhtml page

Running this application and there we have it on JRuby Rails

The virtual machine empowers Java and makes it a platform, not just a technology or programming language. Developers can benefit from MVP and, combining with the power of JVM, can take this pattern to another level.

No Comments »

Teera on February 3rd 2008 in Ruby, Netbeans, Web Dev, Java

Model-View-Presenter pattern in Java

Model-View-Presenter pattern has been around for quite some time. Though it seems that MVP is quite popular among .NET community, I don’t see much adoption in the Java camp. I’ve had quite a number of success on applying MVP to both Java and .NET projects, and have been a fan of this pattern since. On this blog post, I’m going to show you what MVP is, what it can offer, and why Java developers should pay attention to it.

Model-View-Presenter pattern

The key idea of MVP is the UI design that decouple the UI logic and UI representation. This will make the UI layer very thin and relieve it from any responsibilities as much as possible. Consider most of UI technologies come with the UI display and some logic attach to it (for example, binding event or data to Swing control). Having this coupling makes it difficult to automate the test for UI. Worse, if you decide to change the UI technology, you will have to rewrite this UI logic all over again.

MVP suggests the idea of separating UI logic to a separate class, the Presenter. The UI will have only small responsibilities of displaying data to the user and taking input. Two benefits of implementing this pattern are ease of UI testing and reuse of logic code on different presentation technology.

The Model

Model is where you store business logic, service, or data. It’s identical to the Model in Model-View-Controller architecture.

The View

The presentation layer of your application. In the context of MVP, the view should do nothing else but display data to and grab input from users.

The Presenter

You can think of presenter as an abstraction layer that glues the model and the view together. On the implementation level, this is done through the use of interface.

Model-View-Presenter with Swing

OK. Let’s see what the code looks like. Let’s say that I have a small book store application that does the following:

  • Grab list of books from data source and display in a drop-down list.
  • When user selects book from the drop down list, the detail of the book should be displayed on screen.

In normal Swing App, you’ll likely to see UI logic code stuck in actionPerformed method of an anonymous ActionListener class.


Traditional Swing application

However, with MVP, we try to remove UI logic from the view. So, the ActionListener will call presenter to perform this action.


Calling presenter on event

The presenter will join together the data from model and fetch it back to the view. As you can see, by wiring each component through interface, the view and the model are not aware of one another. You get a nice separation of concerns here.

Presenter: get data from model and display to the view
Presenter class: handle the logic, tying view and model together


Model interface: data model provider must implement this interface


View interface that view class must implements

The implementation

Martin Fowler recently broke up MVP to two patterns: Supervising Controller and Passive View (since it’s Mr.Fowler who declared MVP, it’s legit for him to retire it?). The main difference between the two is the level of interaction between each component.

In Passive View pattern, each component has clear boundary. The view contains very few or minimum logic code. Both view and model rely heavily on presenter, this includes the view updating logic.

MVP
Nikola Malovic’s diagram demonstrates a very clean separation between each of the component

Implementing clean separation passive view involves a lot of code. Supervising Controller is very similar to Passive View but more relax. Supervising Controller allows some logic code to be in the view. It also allows the model to talk to the view directly for updating display data.

There are also other flavors of MVP out there. They have the same key ideas of UI decoupling, only the minor difference in how it’s done. I prefer the implementation that can give me the cleanest separation of concern between the view, the model, and the presenter. Neither the view nor the model should have any dependencies on the presenter.

Don’t restrict yourself to the diagram though. There are cases where it’s necessary and better to have the view and model communicate directly to one another. For instance, if your application does not have strong object model, displaying a form with 200 fields from 20 tables to screen can be a daunting task. In this case, you’ll have to create a new object entity class to store all these fields to maintain a clean separation. It’d be much easier and less code involved if the model can update the view directly.

Benefits of MVP

As I mention above, the most evident benefits of MVP are making the UI testable and independent from presentation technology. The topic of testing is tied to Test Driven Development which I will go into detail in future posts.

Extensibility

Recently a client had asked me to port a Java desktop application to the web. Although quite a chunk of time was required to refactor the old code, the porting process was remarkably smooth with MVP. Let’s look at the earlier bookstore example. Assume that we are asked to port this application to web version. For simplicity, let’s say that our web platform is simple Java servlets and JSP.

First, I create a servlet that control a index.jsp. I have this servlet implements IBookDetailView. At this point you may ask why the servlet, isn’t the servlet supposed to be acting as controller/presenter? We already have the presenter logic in place. The servlet here serves as the output channel to the JSP file.

Then inside the servlet’s init() method, I initialize the presenter and the model the same way I do in Swing version.

After implementing all view methods, the servlet is ready to pass down the data in the form of Java Bean to JSP file for display. We now go ahead and add code to the JSP file to display data.

And that’s all we have to do. As you can see, the beauty here is we accomplish this migration task with out having to change any logic or model code. MVP benefits heavily from the use of interface.

Using MVP design pattern can give you the extensibility for building user interface application. MVP in a sense, is a good practice of layering and applying dependency injection to your application.

You can download the source code for the example HERE

For more information on the MVP pattern

No Comments »

Teera on January 29th 2008 in Ruby, Netbeans, Web Dev, Java