Archive for the 'Ruby' Category

ASP.NET MVC Q&A

Last week I presented at BC .NET user group and there are a number of good questions I didn’t have time to answer. So here’s a recap.

Download sample code here

Why would I choose ASP.NET MVC over traditional WebForms?

The answer to this question deserves its own post. So you can read it the answer here. 

I’m an ASP.NET WebForm developer, how difficult is it for me to learn MVC?

Although development on MVC framework is different from WebForms, I don’t think it is difficult at all. In fact, if you are familiar with the MVC pattern, polymorphism, HTML, HTTP, and how the web works in general, you’ll feel right at home with MVC.

The fastest way to get a to know MVC is to create a new blank MVC project in Visual Studio and look at how the  HomeController class, model, view (under the folder Views/Home/Index.aspx), and routing in Global.asax are put together.

From this, you’ll get the basic idea of how MVC wire things up together. After that there are a number of sample applications you can inspect:

These 3 sample applications should be able to demonstrate how you can get MVC to work and how you can effectively leverage the framework and pattern. Also don’t forget to check out loads of tutorial on ASP.NET MVC website

Should I use JQuery with MVC? Can I use other JavaScript library?

ASP.NET MVC is shipped with JQuery (I believe now it’s 1-3.2 version), but you are NOT tied to the library. You can use any client side library you want. My team and I have been using MooTools for most of our MVC projects.

What do you mean when you say that ASP.NET MVC is stateless?

WebForms keep state (original values of ASP.NET controls on a page) inside ViewState. This ViewState is usually stored as a hidden field or inside a session. When an ASP.NET form does a postback, the server side then reads the values kept in the ViewState, restores the controls object model, and allows you to manipulate the values. This is the way ASP.NET WebForms tries to make the web stateful (every controls seem to remember their previous values).

ASP.NET MVC does NOT rely on ViewState. MVC view interacts with the controller (server side) via simple form post request to designated URI. All the values are encapsulated within the HTTP request. The server side controller only works the posted values and return final output of rendered HTML back to the browser.

Can I use both WebForm and MVC in one project?

Yes, you can but it is NOT recommended. In the project I’ve worked on, there are a migration period where we have to have both WebForms and MVC coexist in one project. Although it is possible to have both, it comes with a price of maintainability.

Do I have to use TDD or BDD in MVC project?

You do NOT have to do TDD or BDD in your MVC project. Test-Driven development is a good development principle but MVC is not tied to it.

How can I do databinding in ASP.NET MVC?

Please see the sample code accompanying the presentation. In the source code download, I show 2 ways of data binding, one with using <% foreach %> and another binds to ASP.NET repeater control.

Can I still use user control in MVC? Is there any 3rd party controls or components for MVC?

You can still use user controls in ASP.NET MVC via Partial Rendering. Though you may have to simplify your user control code for consistency with the framework.

AFAIK, I don’t think there’re free controls for ASP.NET MVC released just yet. But you really should check out MVC Contrib project on CodePlex, it offers a lot of helper classes that you will find very useful. On the commercial side, Telerik has released its MVC-Compatible web controls suite.

What about Ruby on Rails?

There were a lot of people showing interest in learning more about Ruby on Rails after the presentation. And I think they definitely should check it out. A lot of good ideas from Ruby on Rails community have been incorporated into MVC framework. But despite what some people would say, I don’t think ASP.NET MVC is intended to be Rails-clone.

I do work on Ruby on Rails as well and they are different. One reason that Rails is cool is because it leverages a lot of dynamic feature of Ruby the language. The only similarity I see between ASP.NET MVC and Ruby on Rails right now is the fact that it implements the MVC pattern and good guiding principles such as Convention over Configuration, DRY, and YAGNI.

If you want to learn and find out more about Ruby on Rails, it’s definitly worth check out this free online course.

Any comment or questions, feel free to leave comment on this post or contact me at teera@zolomedia.com

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.

2 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