September 17, 2008

The “V” in MVC

Filed under: ajax, forms, IDE, MVC, rails, view — oomoo @ 8:42 pm

Probably one of the hardest adjustments to make when transitioning from Desktop forms development to browser-based is the endless number of code and template files that must be created and maintained just to have one working “form” (that you will now be calling a “page”). 

With a traditional desktop form, it usually isn’t hard to get your arms around all of the “players” involved in making your form work.  You may have many “layers/tiers”, but most of the pieces are probably written in the same language using the same IDE.  This is not the case when designing web pages/forms where the content for each page is spread across several files (at a minimum) each of which are probably using very different development languages and/or markup styles.  

Why have all of these “pieces” of code and/or markup all over the place?

  1. MVC (Model View Controller)
    The MVC architecture dictates separation between your data/business logic (model), your application code (controller), and the web page presented to the user (view). The “View” in “MVC” really means “a combination of all the pieces needed to create a finished page/form”. 
  2. DRY (Don’t Repeat Yourself)
    DRY is one tenet of Rails development.  It basically says “if you are copying/pasting the same code/markup into multiple files, that code/markup should be put into it’s own file which should just be pulled into the pages that need it at run-time.”  Yes, that is my own paraphrase 🙂
  3. WWW = Best Of Breed
    Web development has accelerated the pace at which tools and technologies are evolving.  We web developers love to complain about all the “disconnectedness” that exists in web-based apps, but we would really scream if some new technology came out and we had to wait a year for some company to boil out the impurities and then bloat it up so it could be “assimilated” before we could work with it (wait, I know that company…).  HTML, CSS, and JavaScript are poster-child technologies for “survival of the fittest” or should I say “survival of the most flexible but yet most simple”… nah, doesn’t have the same ring to it.

So, with just these three demands placed on us as a pre-requisite for developing a web form, it’s no wonder that we end up with so many disparate technologies and pieces all needing to converge without errors inside multiple versions of non-standard browser implementations across multiple operating systems.  Oh man, my stomach just knotted up right there… okay, Ruby and Rails to the rescue!


Anatomy Of A View

The following “pieces” are used to produce a single web page/form:


The main part of a web page or “form”.  It resides in \app\views\modelname\myview.html.erb.  Many people consider this the “view”, but it is only one component of the view.  This one file actually contains many types of coding/markup/templating.

  • HTML – text, tags, tables, etc.
  • ERB – in-line Ruby including object/variable references, custom method calls, helper method calls, etc.
  • CSS – in-line style settings override external CSS stylesheet settings.
  • JavaScript – in-line JSP method calls  (can also contain JavaScript methods).
  • Images – icons, pictures, borders, backgrounds, etc. located in \public\images\
  • Flash – or Silverlight, or some other 3rd party client control.


Your cascading stylesheet(s) which control most of the presentation properties of your page/form.  You will almost always have at least one of these for each application.  It is very likely that you will have several.

  • CSS stylesheets are stored in \public\stylesheets\.
  • Which stylesheet to use is usually established in either an application-level or a controller-level Layout file like this:  
    <%= stylesheet_link_tag ‘mystyle’ %>



Your JavaScript classes/functions and 3rd party tools like Scriptaculous, Prototype, and JQuery.   Your application will usually use at least 3 JSP libraries.   Large AJAX-driven client applications can have…lots of them!

  • JavaScript code files are stored in \public\javascripts\.
  • Usually, the Layout file will include:
    <%= javascript_include_tag :defaults, :cache => true %>
    which will include the 5 most commonly used javascript libraries (including Scriptaculous and Prototype).
  • You can also specify
    <%= javascript_include_tag :all, :cache => true %>
    which will automatically include EVERY javascript file found in \public\javascripts\
  • You can also specify
    <%= javascript_include_tag ‘prototype’, ‘effects’, ‘controls’, :cache => true %>
    to control which libraries load or the order in which they are loaded.



Helpers blur the line between a Controller and a View.  As Dave Thomas so brilliantly put it, “A helper is simply a module containing methods that assist a view.  Helper methods are output-centric.  They exist to generate HTML (or XML, or JavaScript)-a helper extends the behavior of a template.”

  • Helpers are stored in \app\controllers\helpers\ 
  • Controller-specific Helpers are named after their Controller with “_helper.rb” appended to the end.
  • The Application-wide Helper is \app\controllers\helpers\application_helper.rb


A layout is kind of like an HTML/ERB fragment or snippet that gets pulled into your page template at run-time and is usually used to show data/text on the page this is generic across all views/pages for the Controller (like headers, footers, borders, etc.).   

  • All layouts are stored in \app\views\layouts\
    (defined by the constant TEMPLATE_ROOT)
  • Controller-specific layouts are named after their Controller.
  • The application-wide Layout named “application.html.erb”
  • The application-wide layout can be specified in \app\controllers\application.rb
  • Each Controller can override the application-level layout by setting the “layout” property or by passing
    :layout => ‘layouts/mylayout’
    directly in the render( ) method call.
  • You can suppress the use of any Layout by including
    :layout => false
    in the render( ) method call.


Partials are very much like Controller-level Layouts because they are HTML/ERB fragments that get pulled into your page and rendered at run-time.  The big difference is that Partials are typically used to display repetitive formatted information (like a grid with rows of records) using a code block (DO…END block).

Partials must be manually called for in your HTML/ERB file like this:
<%= render :partial => "clientlist", :locals => { :f => @f, :label_text => "Update"} %>

This will render the partial _clientlist and pass it the local variables (from the Controller) and the set the variable “label_text” to the value "Update"

Rails 2.0 introduced the ability for a Partial to have it’s own Layout.  Yes, it does seem a bit like nesting, but it is nice to have!  Now, we can do something like this in our HTML/ERB file:
<%= render :partial => "header", :Layout => ‘boxed’ :locals => { :post => @post} %>
which will pull in the Layout _boxed.html.erb, which will then pull in the Partial _header.html.erb.

  • Partials are usually used on a “per View basis” and are stored in \app\views\myview\
  • Partials are named beginning with an underscore (i.e.  _mypartial.html.erb)
  • Partial Layouts are stored in the same folder as the Partial and also begin with an underscore.
  • You can re-use a Partial Layout across your application if you store it in

    Then, when calling the partial, just use 
    :layout => ‘layouts\mylayout’


RJS templates also blur the line between the Controller and the View.  They have access to all of the Controller objects/variables, but they also have an object reference to the current HTML “page” that is in the browser.  RJS templates allow you to infuse JavaScript into your views that is written using Rails “helper methods” (instead of actual JavaScript).  Separate RJS template files are not required (you can accomplish most of the same things with “render updates” directly in your Controller code). 

  • RSJ template files are stored in \app\views\myview
  • RJS templates are named for the Controller “Action” from which they are called with a “js.rjs” extension.
  • RJS templates are not actually “called”, if one exists, it is simply applied when the view is rendered.
  • Make sure you don’t try to name an RJS template the same thing as the View, otherwise the View gets rendered, not the RJS.




I just showed you how you could easily have 7 or more separate files using 5 or more different technologies included in the 1 page you are trying to display to the user.  Hopefully, knowing is half the battle and at least the reasons “why” make a little more sense to you now.  I also gave you a fairly concise list of the places where the creation/display of a Ruby On Rails “View” can go wrong.  Using Ruby On Rails can sometimes seem like magic, and that is part of the fun.  But, you at least need to know that there “is” someone behind the curtain and try to get as familiar as you can with the plumbing because one day it will back up!


How To Debug

Debugging an application with hundreds of files and so many combined technologies is no small feat.  The first step is to remember that all of these “pieces” eventually get smashed back together into the HTML displayed in the browser!  So, you can view the source of the page in the browser (Using the IE Developer Toolbar in Internet Explorer, or even better, using the Firebug plugin for FireFox).

Use a full-blown IDE with a built-in debugger (like Aptana with RadRails, Steel Sapphire, Komodo, etc.)

Use the Logs!  Look at your log files, and don’t forget that you can pepper any problem code with manual log entries.

Use the IRB!  The interactive Ruby console will allow you to spy on your objects and variables as well as manipulate them in real-time.  Yes, it’s command-line Alice.

Use some of the great tools and techniques laid out in this post: Rails Guide – Debugging


*This post uses Rails 2.1 and Ruby 1.8.


March 31, 2008

Is Mac “Perfect” for Rails Development?

Filed under: IDE, Linux, mac, rails, Windows — oomoo @ 5:32 pm
I’ve never been a Mac fanboy. I never actually “owned” a Mac either. In fact, it has always pissed me off the way that many of the Rails development blogs just assumed you were using a Mac or possibly Linux, but never (he whispers) “Windows”. The snide little way they would say “Okay class, open your terminal window and type: /script generate blah blah blah”, just assuming that I had a friggin terminal window and that I didn’t have to type “ruby” first.
Microsoft and I have been joined at the brain for quite a number of years now. It’s not the perfect relationship, I’ll admit. Bill doesn’t really listen to what I have to say like he did when things were all new and exciting. He is not interested in my “feelings”. He never asks, “So, how was your development day today?” Although, for a while, he did ask “where do you want to go today?” There have been times when he has gotten me excited about working on a personal project, just to pull the rug out from under me. Sometimes, we would find something to do together, then he’d just lose interest and walk away. I’d yell, “Oh sure, just walk away. Just like you always do when you aren’t the profit center of attention. Bill… look at me, Bill.. why won’t you even look at me!” But he would just keep on walking, leaving me sitting there with a lap full of J++, RDO, Visual InterDev, or our precious love-child Visual FoxPro.
It wasn’t long ago that Steve really started to entice me. He really shined up his Apple with that IPod, then started wearing down my defenses with the MacBook, the iPhone, then we got to a little bit of iTouch, and finally to OS/X. But, I couldn’t make the move, I had too much to lose and the price of change was just too steep. Then one day, we snuck out and were in the computer store, and he kind of nonchalently steers me over to the Mac section; “just to take a look”, he says. Well, it was all clean and nice, so I walk on over and he starts grinning like a schoolboy. There sat the cutest little machine, “it’s a Mac Mini”, he says to me as he is dropping to one knee, “and it’s cheaper than most PCs… besides Bill will never have to know”. I admit that I was swept up in the emotion of it all, and we ended up walking out there hand-in-hand around an extended 3-year warranty.
Now, Bill and I have been really trying to work things out. He showed me that Steel Sapphire has developed one of the slickest IDE’s available for doing Rails in Visual Studio. Just this afternoon, Bill asked me, “Just what does Steve have on his Mac that I don’t have in my Windows”. He stood there pushing his glasses up waiting for an answer. I sighed, then said “It’s just plain ‘easy’ Bill. You always make everything so complicated, and the Mac is fully loaded for Rails development right off the shelf. I don’t have to slave away installing and configuring over a hot CPU all day long, just to find out that everyone can’t agree on what they want. “
No, I’m not leaving Bill, not yet, I’ve got too much invested. But, now that I have Steve, I just can’t give him up. We have too much in common and we really enjoy being around each other. He just “gets” me. And it may be my imagination, but I think he really listens.  Somebody que the screensaver…
So, if you are new to Rails, or are thinking about learning Rails, you don’t “have” to get a Mac. But, if you want a seamless, easy, and enjoyable experience, if you want peace and harmony between your computer, your O/S, and your development, you owe it to yourself to give one a try. In fact, you could probably go down to your local computer store and create a working Rails application right on the demo machine. Try that on any of the non-Mac models! Ruby, Rails, and lots of Gems are already installed and configured. It just works (the first time)!

March 24, 2008

Getting Started Tips

Filed under: hosting, IDE, rails, ruby — oomoo @ 11:30 am

IDE – Integrated Development Environment

There are many Integrated Development Environments (IDE’s) available for the RoR developer. The choices vary a little across operating systems, but most tools are thankfully cross-platform. I hear the majority of the developers working on the RoR “core” use Mac. I also see lots of posts (especially Ruby ones) by the Linux crowd. Very few posts are Windows-specific. Being technology-agnostic, I actually own Windows, Mac, and Linux computers and devices of all shapes and colors. since I am still heavily involved in desktop apps, The majority of my development work is still done on Windows.

On the Mac, many developers are satisfied to use the text editing programs that ship with the O/S. Having used true Integrated Development Environments for so long, I just cannot live without the ability to design-code-test-repeat in the same environment, call me spoiled. I started my development career programming for DOS, writing “C” programs that had to manually manipulate the video buffer just to show a “form”. I have also done a good bit of Unix/Linux administration, so I am comfortable working from a command-line. But, I must say that the need to have various interfaces and command-prompts for running Apache, MySQL, RAKE, and Ruby made me feel like I was taking two steps back in my efforts to move one step forward on the web.

I am so very grateful and forever in debt to the fine cadre of programmers and development shops that are creating really top-notch IDE tools for Ruby and Rails developers. I am just now starting to see a light at the end of the IDE tunnel.

Ruby In Steel (Visual Studio plugin) (Visual Form Designer)
Steel Sapphire’s “Ruby In Steel” plug-in for Visual Studio has put itself on the cutting edge with their “Visual Form Designer”. That’s right folks, the ability to visually design RoR “forms” right in the IDE. In technical terms, it “smooshes” your view, helper, javascript, and css into what the user will see as the final form. You can then drag-n-drop controls on the “form” visually design it, and still get into the code or html and make edits to those. When you are done, it saves all the changes back to their original parts.

I like the safety of this approach, because it gives you one layer of seperation between the “composite” (smooshed together) form and your actual code. This abstraction allows you to do cool things like export the composite out to your favorite HTML editor, then pull it back in. It is also good, because as it is in beta, the tool has lots of bugs left in it. This is a very ambitious project, so I’ll be patient…. is it done yet?

Even aside from the Visual Form Designer, this is a good tool for straight coding and debugging as well. My big gripe, of course, is that it runs inside Visual Studio, which is a pig and a hog and slow and complex and… well, you get the point. It’s hard to be all things to all people and do any one thing really really well. If you are a Microsoft hugger though, you will think all the “crap” is just the way it is for everyone. Well, not so my friend, which is why you should check out some of these other great tools.

Aptana Studio (with RadRails plugin)
I use Aptana Studio every day. It is fast, clean, and quite comprehensive. Oh yeah, it’s FREE. It’s based on Eclipse and handles all things AJAX with aplumb. It also handles development for Adobe AIR, PHP, and iPhone (and it has a completely javascript server-side) if you need any of those things.

Aptana automatically treats your Rails application and associated sub-directories as a “project”, so there’s no need to create/maintain a project file. The real-time debugging support is excellent as is the ability to find/install new “gems” directly from within Aptana.

Heroku is one of the most mind-bending development platforms I have come across. Heroku allows you to code, debug, and run your Rails application using nothing more than your FireFox browser. You can create code, upload/modify your database, and debug from any computer with an Internet connection. It is also “group aware” allowing your programming team to all collaborate within the same development space. Yes, there is source code control and the ability to backup your entire project to your PC anytime you like.

Heroku runs in the Amazon EC2 (elastic computing cloud) that means that server configuration does not exist. Just flip a switch and your Rails app is magically in “production”, nothing extra to configure, update, or support. The “elastic” in EC2 means that it should be quite scalable, allowing you to allocate resources as-needed. All this goodness is currently in Beta, so I don’t have any pricing or comparison statistics on the hosting side. But, even without the hosting, the ability to develop and test your complete Rails application from any PC is very exciting and perhaps the most unique play in the industry!

3rd Rail
3rd Rail is a Ruby/Rails-specific IDE from CodeGear (formerly part of Borland). It is a very nice IDE, but it is very “young” and seemed to lack some of the extra goodies incorporated by some of the more mature contenders. I have used Borland products many times during my development career and have always found them to be very solid and productivity driven. I will need to check back with 3rd Rail in a while to see how they are progressing.

I purchased Komodo when I was playing with Python and Django (as part of my journey to find Rails). Komodo is very well respected in the Python community. Although I have not used it, I saw that Komodo also has a RoR plugin. If you are using Python or want to use both Python and Ruby, you should check out Komodo.


Development Stack (Ruby, Rails, Apache, MySql, SqlLite, etc.)

If you are lazy (I prefer to think of it as “not expending unnecessary cycles”) or you just want a quick way of trying out this whole crazy Ruby On Rails thing, you will want to use a consolidated “development stack”. This simply means that there is a master installer/configuration tool that, with one download, will install and configure all the pieces that go into making a RoR web development platform work. Once the “master install” is done, you have a tightly integrated installation of Apache, Ruby, Rails, and MySQL (or SqlLite or some other open source database) which includes a nice little interface to start/stop all these pieces as needed.


InstantRails is the tried-and-true one of the bunch. It did go through a short period recently where it was no longer supported. This gave rise to BitNami picking up the mantle. But, then InstantRails was once again revived and updated for Rails 2.0. It remains my choice.


I tried BitNami a while back, but had troubles with the integrated install. Once InstantRails supported Rails 2.0, I must admit that I stopped trying BitNami. I may use it on a Virtual PC, just to see if they got all the wrinkles ironed out.


Books (be sure to get books covering Rails 2.0)

There are tons of books covering RoR. Here are a few I found very helpful. Each of them comes from a different viewpoint, so you will benefit by reading multiple books by different authors. You never know which one of them will explain a certain thing in just the right way to make your little lightbulb come on!

Why’s Poignant Guide To Ruby (http://poignantguide.net/ruby/) (fee and very entertaining)
Programming Ruby – The Pragmatic Programmer’s Guide (Dave Thomas) (known as “PickAxe”)
Agile Web Development with Rails (Dave Thomas)
Ajax On Rails (Scott Raymond)
Build Your Own Ruby On Rails Application (Patrick Lenz)
Ruby For Rails (David A. Black)
Beginning Ruby – From Novice to Professional (Peter Cooper)
The Rails Way
The Ruby Way
The Ruby Programming Language


Web Sites (there are also tons of blogs and such)

For in-depth examples and free code, nothing beats the really greats RoR blogs out there!

But, here is a tiny sampler of some of the more “authoritative” Ruby/Rails websites:

Official Rails Site: http://www.rubyonrails.com/
Official Ruby Site: http://www.ruby-lang.org/en/
Offiicial Blog: http://weblog.rubyonrails.org/
API Reference: http://api.rubyonrails.org/
Rails Wiki: http://wiki.rubyonrails.org/rails

PeepCode: http://peepcode.com/
Rails PodCasts: http://podcast.rubyonrails.org/
Rails Workshops: http://rubyonrailsworkshops.com/
Ruby Learning: http://rubylearning.com/

*As my daddy used to tell me (on an almost daily basis) “well son, you’re not gonna learn any younger”.

Create a free website or blog at WordPress.com.