Category: Ruby on Rails

Freezing your Rails at Softies on Rails

I ran across a really good tutorial over at Softies on Rails called “Freezing Your Rails Application“, which details what is means to freeze Rails, how-to do it and other great information:

  • What Freezing Rails Is?
  • Freeze to a particular Rails Version
  • Freeze to Edge Rails
  • Unfreezing

It is great for new and old Rails developers as a reference to how-to manage the freeze process.

Technorati Tags: ,

acts_as_conference looks like the deal of the year

In case anyone has missed the announcement of the upcoming acts_as_conference conference in Orlando, Fl on February 8-9, 2008, act now before it’s sold out. The best part is the conference only costs $100.00. The conference is a two-day Ruby on Rails conference with a great list of speakers and sessions.

Who Should Attend?

  • Ruby on Rails aficionados
  • Web developers and programmers (independent, startup, enterprise/corporate)
  • Developers using other languages/frameworks looking to get started with Ruby on Rails
  • IT managers tracking emerging technologies
  • Tech-savvy entrepreneurs with business ideas looking to compete with a faster time to market
  • Users at every level
  • Business users interested in web technologies and strategic implementation

What’s the Agenda?

Day 1 – Friday, February 8, 2007

7:30 – 8:45am Registration
9:00am – Noon Charity Session – Ezra Zygmuntowicz and Evan Phoenix
1:15 – 1:30pm Welcome
2:30 – 3:30pm Working with others: Best Practices for Rails Teams – Luke Francl
4:00 – 5:00pm Rails on AIR – Peter Armstrong

Day 2 – Saturday, February 9, 2007

8:00 – 9:00 Sponsored breakfast
9:00 – 10:00am Sponsored Talks
11:00 – Noon Shining a Light on the Dark Magic of ActiveRecord – Anthony Eden
1:15 – 1:30pm Housekeeping and Prizes
2:30 – 3:30pm Adding Media to Your Rails Application – Dave Naffis and Josh Owens
4:00 – 5:00pm Lessons from the Trenches – Learning from the Rails Bootcamp – Charles Brian Quinn
6:30 – 6:45pm Closing

I am planning on attending and take what looks to be a great conference. I am not affiliated with the conference at all, just trying to get the word out. Pass it along.

Technorati Tags: ,

Setting up SQLite3 for Ruby on Rails Development

UPDATE: Thanks to an astute reader, it seems to have full SQLite3 support on Windows you need to add the SQLite3.dll and the SQLite3.def files also in your path.  I put these in my ruby/bin folder, which is where they will be in the Instant Rails release coming up.

The release of Ruby on Rails 2.0.2 made some fairly significant changes in the default database for Rails applications.  The default, and standard, database has always been MySql but the Rails team felt it easier for development to use SQLite3 and make it the new default.

Setting up SQLite3 is pretty straight forward both on Windows and the Mac OSX, both Tiger and Leopard come with SQLite3 already installed so that makes the Mac one up on Windows.  My Tiger installation had SQLite3 v3.13 installed on it so I wanted to make sure I had the latest at the time of this writing and put 3.5.4 on it.

Installing on Windows

The installation on Windows was really straight forward.  The main thing is to download the pre-compiled version of SQLite3 3.5.4 from the SQLite web site, unzip it and copy the single sqlite3.exe to my ruby/bin directory.

Now that SQLite3 is installed, just install the gem:

gem install sqlite3-ruby

And that’s it.

Installing/Updating on the Apple Mac OSX

Upgrading my Rails installation was a breeze on my MacBook Pro, after upgrading to RubyGems 1.0 the Rails 2.0.2 install went through without a hitch.  The only real concern I had about upgrading to Rails 2.0.2 on the Mac was the fact the default database for 2.0.2 is SQLite3 and I had an old version.  I feel a bit indifferent about installing over versions of software installed by Apple in the event it is used by something and I break it.  I am pretty new to the Mac and fixing an issue like this can sometimes be intimidating.

I found an older version of SQLite3, here:

/usr/local/bin/sqlite3

There are several ways to update software like this on the Mac and using MacPorts seems to be a popular way to do it, but I chose to install from source.   I have a Source directory in my home folder on my Mac and I simply start everything from there.  So, to install I did the following:

$ curl -O http://www.sqlite.org/sqlite-3.5.4.tar.gz $ tar xzf sqlite-3.5.4.tar.gz $ cd sqlite-3.5.4 $ ./configure --prefix=/usr/local $ make $ sudo make install

After working with Windows systems for most of my professional career I chuckle at how cryptic the commands are in Unix-like environments.  Maybe this is to keep the barrier to entry high.

Using the “which sqlite3″ command should reveal the same location as the original SQLite3 installation.  If you actually type in “sqlite3″ you enter the command mode of SQLite3 and should see the new 3.5.4 version.

The last step to is to install the Ruby driver for SQLite3, accomplished with:

$ sudo gem install sqlite3-ruby

This installed without any problems and was good to go with using SQLite3 on my Mac Rails 2.0.2 installation.  It’s funny though, the Windows installation was very easy and the Mac install took a bit of work that was not particularly obvious.  I thought the Mac was supposed to be so much easier than the PC?  Isn’t this what the Apple ads try to get us to believe?  I guess Apple just has better marketing.

Technorati Tags: ,,,

Ruby on Rails 2.0.1 Available now

According to a post today on the Ruby on Rails blog, Ruby on Rails 2.0 has been released after almost a year in the making.

This release is full of new features, lots of fixes and a large amount of polish.  David (DHH) said about the release:

What a milestone for Ruby on Rails as well. I’ve personally been working on this framework for about four and a half years and we have contributors who’ve been around for almost as long as well. It’s really satisfying to see how far we’ve come in that period of time. That we’ve proven the initial hype worthy, that we’ve been able to stick with it and continue to push the envelope.

The list of What’s New with this release is long.   The major ones which will interest Rails developers most include:

  • Action Pack: Resources

This is where the bulk of the action for 2.0 has gone. We’ve got a slew of improvements to the RESTful lifestyle. First, we’ve dropped the semicolon for custom methods instead of the regular slash. So /people/1;edit is now /people/1/edit. We’ve also added the namespace feature to routing resources that makes it really easy to confine things like admin interfaces:

map.namespace(:admin) do |admin| admin.resources :products, :collection => { :inventory => :get }, :member => { :duplicate => :post }, :has_many => [ :tags, :images, :variants ] end

Which will give you named routes like inventory_admin_products_url and admin_product_tags_url. To keep track of this named routes proliferation, we’ve added the “rake routes” task, which will list all the named routes created by routes.rb.

We’ve also instigated a new convention that all resource-based controllers will be plural by default. This allows a single resource to be mapped in multiple contexts and still refer to the same controller. Example:

 # /avatars/45 => AvatarsController#show map.resources :avatars # /people/5/avatar => AvatarsController#show map.resources :people, :has_one => :avatar 

  • Action Pack: Multiview

Alongside the improvements for resources come improvements for multiview. We already have #respond_to, but we’ve taken it a step further and made it dig into the templates. We’ve separated the format of the template from its rendering engine. So show.rhtml now becomes show.html.erb, which is the template that’ll be rendered by default for a show action that has declared format.html in its respond_to. And you can now have something like show.csv.erb, which targets text/csv, but also uses the default ERB renderer.

So the new format for templates is action.format.renderer. A few examples:

  • show.erb: same show template for all formats
  • index.atom.builder: uses the Builder format, previously known as rxml, to render an index action for the application/atom+xml mime type
  • edit.iphone.haml: uses the custom HAML template engine (not included by default) to render an edit action for the custom Mime::IPHONE format

Speaking of the iPhone, we’ve made it easier to declare “fake” types that are only used for internal routing. Like when you want a special HTML interface just for an iPhone.

  • Action Pack: Record identification

Piggy-backing off the new drive for resources are a number of simplifications for controller and view methods that deal with URLs. We’ve added a number of conventions for turning model classes into resource routes on the fly. Examples:

 # person is a Person object, which by convention will # be mapped to person_url for lookup redirect_to(person) link_to(person.name, person) form_for(person) 
  • Action Pack: HTTP Loving

As you might have gathered, Action Pack in Rails 2.0 is all about getting closer with HTTP and all its glory. Resources, multiple representations, but there’s more. We’ve added a new module to work with HTTP Basic Authentication, which turns out to be a great way to do API authentication over SSL. It’s terribly simple to use. Here’s an example (there are more in ActionController::HttpAuthentication):

 class PostsController < ApplicationController USER_NAME, PASSWORD = "dhh", "secret" before_filter :authenticate, :except => [ :index ] def index render :text => "Everyone can see me!" end def edit render :text => "I'm only accessible if you know the password" end private def authenticate authenticate_or_request_with_http_basic do |user_name, password| user_name == USER_NAME && password == PASSWORD end end end 

We’ve also made it much easier to structure your JavaScript and stylesheet files in logical units without getting clobbered by the HTTP overhead of requesting a bazillion files. Using javascript_include_tag(:all, :cache => true) will turn public/javascripts/.js into a single public/javascripts/all.js file in production, while still keeping the files separate in development, so you can work iteratively without clearing the cache.

Along the same lines, we’ve added the option to cheat browsers who don’t feel like pipelining requests on their own. If you set ActionController::Base.asset_host = “assets%d.example.com”, we’ll automatically distribute your asset calls (like image_tag) to asset1 through asset4. That allows the browser to open many more connections at a time and increases the perceived speed of your application.

  • Action Pack: Security

Making it even easier to create secure applications out of the box is always a pleasure and with Rails 2.0 we’re doing it from a number of fronts. Most importantly, we now ship we a built-in mechanism for dealing with CRSF attacks. By including a special token in all forms and Ajax requests, you can guard from having requests made from outside of your application. All this is turned on by default in new Rails 2.0 applications and you can very easily turn it on in your existing applications using ActionController::Base.protect_from_forgery (see ActionController::RequestForgeryProtection for more).

We’ve also made it easier to deal with XSS attacks while still allowing users to embed HTML in your pages. The old TextHelper#sanitize method has gone from a black list (very hard to keep secure) approach to a white list approach. If you’re already using sanitize, you’ll automatically be granted better protection. You can tweak the tags that are allowed by default with sanitize as well. See TextHelper#sanitize for details.

Finally, we’ve added support for HTTP only cookies. They are not yet supported by all browsers, but you can use them where they are.

  • Action Pack: Exception handling

Lots of common exceptions would do better to be rescued at a shared level rather than per action. This has always been possible by overwriting rescue_action_in_public, but then you had to roll out your own case statement and call super. Bah. So now we have a class level macro called rescue_from, which you can use to declaratively point certain exceptions to a given action. Example:

 class PostsController < ApplicationController rescue_from User::NotAuthorized, :with => :deny_access protected def deny_access ... end end 

  • Action Pack: Cookie store sessions

The default session store in Rails 2.0 is now a cookie-based one. That means sessions are no longer stored on the file system or in the database, but kept by the client in a hashed form that can’t be forged. This makes it not only a
lot faster than traditional session stores, but also makes it zero maintenance. There’s no cron job needed to clear out the sessions and your server won’t crash because you forgot and suddenly had 500K files in tmp/session.

  • Action Pack: New request profiler

Figuring out where your bottlenecks are with real usage can be tough, but we just made it a whole lot easier with the new request profiler that can follow an entire usage script and report on the aggregate findings. You use it like this:

 $ cat login_session.rb get_with_redirect '/' say "GET / => #{path}" post_with_redirect '/sessions', :username => 'john', :password => 'doe' say "POST /sessions => #{path}" $ ./script/performance/request -n 10 login_session.rb 

And you get a thorough breakdown in HTML and text on where time was spent and you’ll have a good idea on where to look for speeding up the application.

  • Action Pack: Miscellaneous

Also of note is AtomFeedHelper, which makes it even simpler to create Atom feeds using an enhanced Builder syntax

  • Active Record: Performance

Active Record has seen a gazillion fixes and small tweaks, but it’s somewhat light on big new features. Something new that we have added, though, is a very simple Query Cache, which will recognize similar SQL calls from within the same request and return the cached result. This is especially nice for N+1 situations that might be hard to handle with :include or other mechanisms. We’ve also drastically improved the performance of fixtures, which makes most test suites based on normal fixture use be 50-100% faster.

  • Active Record: Sexy migrations

There’s a new alternative format for declaring migrations in a slightly more efficient format. Before you’d write:

create_table :people do |t| t.column, "account_id", :integer t.column, "first_name", :string, :null => false t.column, "last_name", :string, :null => false t.column, "description", :text t.column, "created_at", :datetime t.column, "updated_at", :datetime end

Now you can write:

create_table :people do |t| t.integer :account_id t.string :first_name, :last_name, :null => false t.text :description t.timestamps end

  • Active Record: Foxy fixtures

Having to relate fixtures through the ids of their primary keys is no fun. That’s been addressed now and you can write fixtures like this:

 # sellers.yml shopify: name: Shopify # products.yml pimp_cup: seller: shopify name: Pimp cup 

As you can see, it’s no longer necessary to declare the ids of the fixtures and instead of using seller_id to refer to the relationship, you just use seller and the name of the fixture.

  • Active Record: XML in, JSON out

Active Record has supported serialization to XML for a while. In 2.0 we’ve added deserialization too, so you can say Person.new.from_xml(“David“) and get what you’d expect. We’ve also added serialization to JSON, which supports the same syntax as XML serialization (including nested associations). Just do person.to_json and you’re ready to roll.

  • Active Record: Shedding some weight

To make Active Record a little leaner and meaner, we’ve removed the acts_as_XYZ features and put them into individual plugins on the Rails SVN repository. So say you’re using acts_as_list, you just need to do ./script/plugin install acts_as_list and everything will move along like nothing ever happened.

A little more drastic, we’ve also pushed all the commercial database adapters into their own gems. So Rails now only ships with adapters for MySQL, SQLite, and PostgreSQL. These are the databases that we have easy and willing access to test on. But that doesn’t mean the commercial databases are left out in the cold. Rather, they’ve now been set free to have an independent release schedule from the main Rails distribution. And that’s probably a good thing as the commercial databases tend to require a lot more exceptions and hoop jumping on a regular basis to work well.

The commercial database adapters now live in gems that all follow the same naming convention: activerecord-XYZ-adapter. So if you gem install activerecord-oracle-adapter, you’ll instantly have Oracle available as an adapter choice in all the Rails applications on that machine. You won’t have to change a single line in your applications to take use of it.

That also means it’ll be easier for new database adapters to gain traction in the Rails world. As long as you package your adapter according to the published conventions, users just have to install the gem and they’re ready to roll.

  • Active Record: with_scope with a dash of syntactic vinegar

ActiveRecord::Base.with_scope has gone protected to discourage people from misusing it in controllers (especially in filters). Instead, it’s now encouraged that you only use it within the model itself. That’s what it was designed for and where it logically remains a good fit. But of course, this is all about encouraging and discouraging. If you’ve weighed the pros and the cons and still want to use with_scope outside of the model, you can always call it through .send(:with_scope).

  • ActionWebService out, ActiveResource in

It’ll probably come as no surprise that Rails has picked a side in the SOAP vs REST debate. Unless you absolutely have to use SOAP for integration purposes, we strongly discourage you from doing so. As a naturally extension of that, we’ve pulled ActionWebService from the default bundle. It’s only a gem install actionwebservice away, but it sends an important message none the less.

At the same time, we’ve pulled the new ActiveResource framework out of beta and into the default bundle. ActiveResource is like ActiveRecord, but for resources. It follows a similar API and is configured to Just Work with Rails applications using the resource-driven approach. For example, a vanilla scaffold will be accessible by ActiveResource.

  • Rails: The debugger is back

To tie it all together, we have a stream of improvements for Rails in general. My favorite amongst these is the return of the breakpoint in form of the debugger. It’s a real debugger too, not just an IRB dump. You can step back and forth, list your current position, and much more. It’s all coming from the gracious note of the ruby-debug gem. So you’ll have to install that for the new debugger to work.

To use the debugger, you just install the gem, put “debugger” somewhere in your application, and then start the server with—debugger or -u. When the code executes the debugger command, you’ll have it available straight in the terminal running the server. No need for script/breakpointer or anything else. You can use the debugger in your tests too.

  • Rails: Clean up your environment

Before Rails 2.0, config/environment.rb files every where would be clogged with all sorts of one-off configuration details. Now you can gather those elements in self-contained files and put them under config/initializers and they’ll automatically be loaded. New Rails 2.0 applications ship with two examples in form of inflections.rb (for your own pluralization rules) and mime_types.rb (for your own mime types). This should ensure that you need to keep nothing but the default in config/environment.rb.

  • Rails: Easier plugin order

e>

Now that we’ve yanked out a fair amount of stuff from Rails and into plugins, you might well have other plugins that depend on this functionality. This can require that you load, say, acts_as_list before your own acts_as_extra_cool_list plugin in order for the latter to extend the former.

Before, this required that you named all your plugins in config.plugins. Major hassle when all you wanted to say was “I only care about acts_as_list being loaded before everything else”. Now you can do exactly that with config.plugins = [ :acts_as_list, :all ].

Upgrading

If you have existing Rails applications and want to upgrade to Rails 2.0, moving first to Rails 1.2.6 is the recommended path.  The reason for this is because 1.2.6 includes deprecation warnings and if you application runs on 1.2.6 with no warning, then it should work fine in Rails 2.0.

I was able to upgrade my primary development system with the simple command:

gem install rails --include-dependencies

and had a Rails 2.0.1 up and running.  I tried later to upgrade a couple other development system but faced a couple errors which I attribute to everyone in the world trying to upgrade at the same time.

Resources

Ryan Daigle has a very good post on his blog Ryan’s Scraps where he has been documenting the changes coming in Rails over the last few months.  Ryan also has a nice PDF you can pick up from Peepcode for only $9, well worth the 146 or so pages.

Two other resources to get you going on Rails 2.0 is a book from long-time Rails guy Obie Fernandez, his book is The Rails Way and the other is Advanced Rails Recipes : 72 New Ways to Build Stunning Rails Apps published by the Pragmatic Programmers and written by Mike Clark.

I am looking forward to getting up-to-speed on the latest Rails features.  I have a few applications I plan to start upgrading and one I will be starting clean with Rails 2.0.

Technorati Tags:

The Rails Way has Come My Way

0321445619_500

Yes, my copy of The Rails Way by Obie Fernandez arrived today via Fed Ex.  My copy arrived by way of Obie as I was quoted in the back of the book describing what the Rails way means to me. 

I just received the book so I can say much about it, other than after browsing through it.  It does look like a great book and it covers Rails 2.0, the upcoming release.   This is the first book I have seen covering Rails 2.o and looks to cover the more complex parts of Rails.

The forward is written by David H. Hanson and from the back cover:

  • Increase your productivity as a web developer
  • Realize the overall joy of programming with Ruby on Rails
  • Learn what’s new in Rails 2.0
  • Drive design and protect long-term maintainability with TestUnit and RSpec
  • Understand and manage complex program flow in Rails controllers
  • Leverage Rails’ support for designing REST-compliant APIs
  • Master sophisticated Rails routing concepts and techniques
  • Examine and troubleshoot Rails routing
  • Make the most of ActiveRecord object-relational mapping
  • Utilize Ajax within your Rails applications
  • Incorporate logins and authentication into your application
  • Extend Rails with the best third-party plug-ins and write your own
  • Integrate email services into your applications with ActionMailer
  • Choose the right Rails production configurations
  • Streamline deployment with Capistrano

Thanks Obie!  I am looking forward to digging in on this one.

Rails 2.0: Preview Release Available Now!

The Riding Rails blog had a post over the weekend announcing the first preview release of Rails 2.0.  This is exciting news to anyone waiting for the latest release of Rails and who has been running on Edge for a while. Extracted from the Ruby on Rails blog, you can see a list of new features and those removed and put into plug-ins instead:

Action Pack: Resources This is where the bulk of the action for 2.0 has gone. We’ve got a slew of improvements to the RESTful lifestyle. First, we’ve dropped the semicolon for custom methods instead of the regular slash. So /people/1;edit is now /people/1/edit. We’ve also added the namespace feature to routing resources that makes it really easy to confine things like admin interfaces:
map.namespace(:admin) do |admin| admin.resources :products, :collection => { :inventory => :get }, :member => { :duplicate => :post }, :has_many => [ :tags, :images, :variants ] end

Which will give you named routes like inventory_admin_products_url and admin_product_tags_url. To keep track of this named routes proliferation, we’ve added the “rake routes” task, which will list all the named routes created by routes.rb. We’ve also instigated a new convention that all resource-based controllers will be plural by default. This allows a single resource to be mapped in multiple contexts and still refer to the same controller. Example:

 # /avatars/45 => AvatarsController#show map.resources :avatars # /people/5/avatar => AvatarsController#show map.resources :people, :has_one => :avatar  

Action Pack: Multiview Alongside the improvements for resources come improvements for multiview. We already have #respond_to, but we’ve taken it a step further and made it dig into the templates. We’ve separated the format of the template from its rendering engine. So show.rhtml now becomes show.html.erb, which is the template that’ll be rendered by default for a show action that has declared format.html in its respond_to. And you can now have something like show.csv.erb, which targets text/csv, but also uses the default ERB renderer. So the new format for templates is action.format.renderer. A few examples:

  • show.erb: same show template for all formats
  • index.atom.builder: uses the Builder format, previously known as rxml, to render an index action for the application/atom+xml mime type
  • edit.iphone.haml: uses the custom HAML template engine (not included by default) to render an edit action for the custom Mime::IPHONE format

Speaking of the iPhone, we’ve made it easier to declare “fake” types that are only used for internal routing. Like when you want a special HTML interface just for an iPhone. All it takes is something like this:

 # should go in config/initializers/mime_types.rb Mime.register_alias "text/html", :iphone class ApplicationController < ActionController::Base before_filter :adjust_format_for_iphone private def adjust_format_for_iphone if request.env["HTTP_USER_AGENT"] && request.env["HTTP_USER_AGENT"][/(iPhone|iPod)/] request.format = :iphone end end end class PostsController < ApplicationController def index respond_to do |format| format.html # renders index.html.erb format.iphone # renders index.iphone.erb end end end 

You’re encouraged to declare your own mime-type aliases in the config/initializers/mime_types.rb file. This file is included by default in all new applications. Action Pack: Record identification Piggy-backing off the new drive for resources are a number of simplifications for controller and view methods that deal with URLs. We’ve added a number of conventions for turning model classes into resource routes on the fly. Examples:

 # person is a Person object, which by convention will # be mapped to person_url for lookup redirect_to(person) link_to(person.name, person) form_for(person)  
  

Action Pack: HTTP Loving As you might have gathered, Action Pack in Rails 2.0 is all about getting closer with HTTP and all its glory. Resources, multiple representations, but there’s more. We’ve added a new module to work with HTTP Basic Authentication, which turns out to be a great way to do API authentication over SSL. It’s terribly simple to use. Here’s an example (there are more in ActionController::HttpAuthentication):

 class PostsController < ApplicationController USER_NAME, PASSWORD = "dhh", "secret" before_filter :authenticate, :except => [ :index ] def index render :text => "Everyone can see me!" end def edit render :text => "I'm only accessible if you know the password" end private def authenticate authenticate_or_request_with_http_basic do |user_name, password| user_name == USER_NAME && password == PASSWORD end end end 

We’ve also made it much easier to structure your JavaScript and stylesheet files in logical units without getting clobbered by the HTTP overhead of requesting a bazillion files. Using javascript_include_tag(:all, :cache => true) will turn public/javascripts/.js into a single public/javascripts/all.js file in production, while still keeping the files separate in development, so you can work iteratively without clearing the cache. Along the same lines, we’ve added the option to cheat browsers who don’t feel like pipelining requests on their own. If you set ActionController::Base.asset_host = “assets%d.example.com”, we’ll automatically distribute your asset calls (like image_tag) to asset1 through asset4. That allows the browser to open many more connections at a time and increases the perceived speed of your application. Action Pack: Security Making it even easier to create secure applications out of the box is always a pleasure and with Rails 2.0 we’re doing it from a number of fronts. Most importantly, we now ship we a built-in mechanism for dealing with CRSF attacks. By including a special token in all forms and Ajax requests, you can guard from having requests made from outside of your application. All this is turned on by default in new Rails 2.0 applications and you can very easily turn it on in your existing applications using ActionController::Base.protect_from_forgery (see ActionController::RequestForgeryProtection for more). We’ve also made it easier to deal with XSS attacks while still allowing users to embed HTML in your pages. The old TextHelper#sanitize method has gone from a black list (very hard to keep secure) approach to a white list approach. If you’re already using sanitize, you’ll automatically be granted better protection. You can tweak the tags that are allowed by default with sanitize as well. See TextHelper#sanitize for details. Finally, we’ve added support for HTTP only cookies. They are not yet supported by all browsers, but you can use them where they are. Action Pack: Exception handling Lots of common exceptions would do better to be rescued at a shared level rather than per action. This has always been possible by overwriting rescue_action_in_public, but then you had to roll out your own case statement and call super. Bah. So now we have a class level macro called rescue_from, which you can use to declaratively point certain exceptions to a given action. Example:

 class PostsController < ApplicationController rescue_from User::NotAuthorized, :with => :deny_access protected def deny_access ... end end 

Action Pack: Miscellaneous Also of note is AtomFeedHelper, which makes it even simpler to create Atom feeds using an enhanced Builder syntax. Simple example:

 # index.atom.builder: atom_feed do |feed| feed.title("My great blog!") feed.updated((@posts.first.created_at
)) for post in @posts feed.entry(post) do |entry| entry.title(post.title) entry.content(post.body, :type => 'html') entry.author do |author| author.name("DHH") end end end end 

We’ve made a number of performance improvements, so asset tag calls are now much cheaper and we’re caching simple named routes, making them much faster too. Finally, we’ve kicked out in_place_editor and autocomplete_for into plugins that live on the official Rails SVN. Active Record: Performance Active Record has seen a gazillion fixes and small tweaks, but it’s somewhat light on big new features. Something new that we have added, though, is a very simple Query Cache, which will recognize similar SQL calls from within the same request and return the cached result. This is especially nice for N+1 situations that might be hard to handle with :include or other mechanisms. We’ve also drastically improved the performance of fixtures, which makes most test suites based on normal fixture use be 50-100% faster. Active Record: Sexy migrations There’s a new alternative format for declaring migrations in a slightly more efficient format. Before you’d write:

create_table :people do |t| t.column, "account_id", :integer t.column, "first_name", :string, :null => false t.column, "last_name", :string, :null => false t.column, "description", :text t.column, "created_at", :datetime t.column, "updated_at", :datetime end

Now you can write:

create_table :people do |t| t.integer :account_id t.string :first_name, :last_name, :null => false t.text :description t.timestamps end

Active Record: XML in, JSON out Active Record has supported serialization to XML for a while. In 2.0 we’ve added deserialization too, so you can say Person.new.from_xml(“David“) and get what you’d expect. We’ve also added serialization to JSON, which supports the same syntax as XML serialization (including nested associations). Just do person.to_json and you’re ready to roll. Active Record: Shedding some weight To make Active Record a little leaner and meaner, we’ve removed the acts_as_XYZ features and put them into individual plugins on the Rails SVN repository. So say you’re using acts_as_list, you just need to do ./script/plugin install acts_as_list and everything will move along like nothing ever happened. A little more drastic, we’ve also pushed all the commercial database adapters into their own gems. So Rails now only ships with adapters for MySQL, SQLite, and PostgreSQL. These are the databases that we have easy and willing access to test on. But that doesn’t mean the commercial databases are left out in the cold. Rather, they’ve now been set free to have an independent release schedule from the main Rails distribution. And that’s probably a good thing as the commercial databases tend to require a lot more exceptions and hoop jumping on a regular basis to work well. The commercial database adapters now live in gems that all follow the same naming convention: activerecord-XYZ-adapter. So if you gem install activerecord-oracle-adapter, you’ll instantly have Oracle available as an adapter choice in all the Rails applications on that machine. You won’t have to change a single line in your applications to take use of it. That also means it’ll be easier for new database adapters to gain traction in the Rails world. As long as you package your adapter according to the published conventions, users just have to install the gem and they’re ready to roll. Active Record: with_scope with a dash of syntactic vinegar ActiveRecord::Base.with_scope has gone protected to discourage people from misusing it in controllers (especially in filters). Instead, it’s now encouraged that you only use it within the model itself. That’s what it was designed for and where it logically remains a good fit. But of course, this is all about encouraging and discouraging. If you’ve weighed the pros and the cons and still want to use with_scope outside of the model, you can always call it through .send(:with_scope). ActionWebService out, ActiveResource in It’ll probably come as no surprise that Rails has picked a side in the SOAP vs REST debate. Unless you absolutely have to use SOAP for integration purposes, we strongly discourage you from doing so. As a naturally extension of that, we’ve pulled ActionWebService from the default bundle. It’s only a gem install actionwebservice away, but it sends an important message none the less. At the same time, we’ve pulled the new ActiveResource framework out of beta and into the default bundle. ActiveResource is like ActiveRecord, but for resources. It follows a similar API and is configured to Just Work with Rails applications using the resource-driven approach. For example, a vanilla scaffold will be accessible by ActiveResource. ActiveSupport There’s not all that much new in ActiveSupport. We’ve a host of new methods like Array#rand for getting a random element from an array, Hash#except to filter down a hash from undesired keys and lots of extensions for Date. We also made testing a little nicer with assert_difference. Short of that, it’s pretty much just fixes and tweaks. Action Mailer This is a very modest update for Action Mailer. Besides a handful of bug fixes, we’ve added the option to register alternative template engines and assert_emails to the testing suite, which works like this:

  1. Assert number of emails delivered within a block: assert_emails 1 do post :signup, :name => ‘Jonathan’ end

Rails: The debugger is back To tie it all together, we have a stream of improvements for Rails in general. My favorite amongst these is the return of the breakpoint in form of the debugger. It’s a real debugger too, not just an IRB dump. You can step back and forth, list your current position, and much more. It’s all coming from the gracious note of the ruby-debug gem. So you’ll have to install that for the new debugger to work. To use the debugger, you just install the gem, put “debugger” somewhere in your application, and then start the server with—debugger or -u. When the code executes the debugger command, you’ll have it available straight in the terminal running the server. No need for script/breakpointer or anything else. You can use the debugger in your tests too. Rails: Clean up your environment Before Rails 2.0, config/environment.rb files every where would be clogged with all sorts of one-off configuration details. Now you can gather those elements in self-contained files and put them under config/initializers and they’ll automatically be loaded. New Rails 2.0 applications ship with two examples in form of inflections.rb (for your own pluralization rules) and mime_types.rb (for your own mime types). This should ensure that you need to keep nothing but the default in config/environment.rb. Rails: Easier plugin order Now that we’ve yanked out a fair amount of stuff from Rails and into plugins, you might well have other plugins that depend on this functionality. This can require that you load, say, acts_as_list before your own acts_as_extra_cool_list plugin in order for the latter to extend the former. Before, this required that you named all your plugins in config.plugins. Major hassle when all you wanted to say was “I only care about acts_as_list being loaded before everything else”. Now you can do exactly that with config.plugins = [ :acts_as_list, :all ].

These improvements shows the thought and commitment by the Rails core team to keeping it simple.  Taking things out that keep the framework light but keeping them available as plug-ins is a great way to do it.

Technorati Tags: , , Rails 2.0

FiveRuns™ + RM-Install = Rails on Linux

One of the reasons I went with VMWare Workstation 6.0 was their support of Linux distributions.  I am a Windows XP user and developer and spend my day using it.  I used Microsoft Virtual PC for working with other operating systems other than Windows XP, but VPC never has done a great job hosting Linux. 

My goal is to become proficient with Linux (Ubuntu) and Ruby on Rails development on that platform.   VMWare Workstation does such an outstanding job of running Linux.

I don’t want to go off on a VMWare tangent, I want to talk about a company named Fiveruns.  Fiveruns is a company who has dedicated themselves to enterprise management for Rails.   This is all they do and they seem to be very good at it.

One of their products is called RM-Install.  RM-Install is a free download that will allow a less than savvy Linux user (me) to get a full Rails stack up and running in no time.  RM-Install actually will install the stack on Linux as well as Mac OSX and a Windows version is coming.

You have to register for a download and you get a single file which is executed and installs and configures the following:

  • Ruby 1.8.6
  • Rails 1.2.3
  • MySQL 5.0
  • SQLite 3.3
  • Subversion 1.4
  • Apache HTTP Server 2.2 (Production mode)
  • OpenSSL
  • ImageMagick 6.3
  • Mongrel/Mongrel Cluster
  • Capistrano
  • Gruff
  • Rake
  • RMagick

It takes only a few minutes to install and when done you are ready to go, no more to do but open a terminal window and create your Rails application.  The installation has a couple options, one for a development platform (no Apache) and a production mode (with Apache).

After I finished the install I created a Rails app, started Mongrel and browsed to http://localhost:3000 and I got the default Rails application page.  No, not magic but it demonstrates how easy it is use RM-Install to get up and running FAST.

The Fiveruns web site is done very well (using Rails) and has some good information about RM-Install and their other products. 

Technorati Tags: ,

Repsonding to Comments About Rails – Scott Bellware [MVP]

There has been some really good discussions going on in the blog world about the Rails vs. .NET debate (MonoRail in particular), if you want to call it that.

I posted recently here about the subject from reasoning in my own mind and to foster the discussion on my blog.   

Scott Bellware has had a series of blog posts on the subject and today posted with his comments about recent comments.  I think the debate is very healthy and shows the passion from both sides.  What is particularly interesting to me is Scott is a Microsoft MVP, so he has an investment in Microsoft technologies but is very passionate about Ruby and Rails.

Scott has a previous post talking about MonoRail vs. Rails which is also worth the time to read.

The comments posted are also worth reading, all very good.

Technorati Tags: , , ,

Why not just use Ruby on Rails?

I have been following a couple projects lately who attempt to make .NET look and act more like Ruby on Rails.  The first one is the Castle Project who have their implementation of ActiveRecord and a Rails-like MVC (model view controller) web framework MonoRail.

Another project is SubSonic which is basically a utility that generates a Data Access Layer for your project and turns your database tables into entities in code.  SubSonic was inspired by Ruby on Rails and the creator is trying to apply some MVC principles to it.

There is an ongoing debate between both of these camps as to why MonoRail is the purest ASP.NET MVC framework and why the SubSonic implmentation is not, Ayende makes some great points here.  Make sure to read the comments as Rob Conery, the SubSonic creator has good follow-up.

I created a test web application using MonoRail and this implementation is as close to Rails in .NET that I have seen.  It takes advantage of handlers and makes the controller be the central point of control in a .NET web application unlike ASP.NET WebForms, where the view is the obvious controller. 

SubSonic does a good job but I don’t think it’s fair to say they are even close to implementing an MVC pattern, data broker yes but not MVC.  This is OK, nothing wrong with the implementation.  I have done a couple small projects with SubSonic and it works very well.

Jeffrey Palermo talks about Microsoft creating an MVC framework for ASP.NET.  I was surprised to see this but I guess Microsoft wants in on the Rails goodness too.

So with all of these people trying to “cash-in” on Rails and all that is good, why not just use Rails?  Why try to take an architecture, ASP.NET WebForms, and make it something it is not?  The square peg in the round hole idea comes to mind.  Using a tool that is right for the job makes the most sense.  Sure, MonoRail comes close but it is not Rails, it is not as clean an MVC implementation as Rails from a developer stand point.  Why not use Rails when it’s the right tool? 

What about IronRuby?

Since hearing about Microsoft’s IronRuby project and bringing a supported implementation of Ruby on the CLR I can only imagine the possibilities.  Once the implementation is Ruby 1.8.x feature-complete it will only be a matter of time when Rails is running on IronRuby, this will be a good day for the MVC fans indeed.   This will be the day it all comes together for Ruby and C# or whatever your favorite CLR language is, to be writing code it it will all just play nicely together.  I think the most important aspect to Microsoft’s success with Ruby will be keeping pure and focusing on the core Ruby path and not adding the Microsoft-esque features probably desirable by the internal language group.  While Jon Lam is driving the product I think they will be good.

Martin Fowler has an interesting post about Ruby Microsoft as does Ola Bini and Charles Nutter (Mr. JRuby).

I don’t talk about JRuby as I am not a Java guy and don’t spend any time writing Java code.  My feeling is that JRuby was really validated once Rails ran on it.  Since Rails is the Ruby “killer app”, it stands to reason that once you can run Rails you have arrived.   This will be the arriving point for IronRuby, running Rails.

I don’t know if we will ever see a truly embraced MVC implementation on the CLR if it is not Rails or some future Rails-derived-cousin.  Some people think Microsoft won’t let Rails be successful on the CLR, which is pure garbage.  When all is said and done, Microsoft wants to sell server licenses and if they do it because of ASP.NET WebForms or Rails on the CLR, it doesn’t matter to them and frankly, shouldn’t matter to the developer.  Again, pick the right tool for the job on a platform you can support.

Rails will run on the CLR one way or another, either from Microsoft or another open source project.  It is just a matter of time.

Rails in a Windows World

My day job consists of writing both Windows applications or web applications that run on Windows web servers.   Most of my code is C# and using SQL Server 2005 to store the data, it pays the bills. I have been working with Ruby on Rails for the past year to year an a half.  I really like Rails as it is very well thought out and implements some very nice standard patterns of application architecture, namely MVC (model view controller). I have tried many ways to run Rails but keep trying to come back to what I know, Windows.    My journey consisted of :

  • Linux (virtualized) – I used a Virtual PC at first and install Fedora Core, Debian, Suse and Ubuntu, installed Ruby, gems and Rails, no problem.
  • Linux (native) – I setup both Fedora and Ubuntu, installed Ruby, gems and Rails, no problem.

All the Linux distributions, either native or virtual worked well for the install but I got into trouble was attempting to setup Apache and MySQL.   My ignorance of  Linux was my downfall, Linux is great and I will probably end up deploying on Linux the learning curve too much.  There are so many ways to configure Apache and MySql posted on the web to make my head spin. I have noticed some companies are creating “Rails Stacks” for Linux that are standard installs of Linux, Ruby, Rails, web server (Apache and/or Mongrel) and a database.   Railsmachine announced just such a stack, as did Thoughtworks. I also decided to go the route of what all the other “pure” Rails developers do and use a Mac.  Yes, I said it, I bought a nice new Apple MacBook Pro and installed TextMate along with Rails on it.  I found out rather quickly that OSX is nothing more than Linux with a shiny cover.  I used the MacBook for a few weeks but found the UI irritating and lacking in usability.  Sure, it could have just been my many years of Windows hurting my Mac productivity, but it felt more like I was trying to be productive in a cartoon. I did enjoy TextMate, it was a very good text editor in an otherwise poor development environment. With all of the beating Microsoft gets for it practices and it’s products, I admit they do a very good job giving developers great tools.  I have become accustomed to Visual Studio and Intellisense.  Try finding any resemblance of Intellisense on your Mac environment, good luck, it’s not there.    Intellisense makes my productivity go way up.

Rails on Windows

I decided instead of forcing myself into Linux or some cousin thereof, I would stick with Windows and figure out the best way for me to do Rails development. There are a couple different ways to get Ruby and Rails running on Windows.  You can either install each individual component (Ruby, Ruby Gems, Rails) or install as a package or stack.  The easiest way to get up-and-running fast is to download and install Instant Rails.  I have to give these guys credit, they take all of the work out of getting a full Rails implementation running on Windows.  InstantRails includes everything you need; Ruby, Ruby Gems, Rails, Mongrel (web server), MySQL, phpMyAdmin and some sample applications.  You have the full environment so you can install whatever gems you may need. I decided to use Instant Rails in conjunction with setting up and running Rails separate, primarily for the experience and to have the most flexibility on my system. I started with installing Ruby (One-Click installer) and Ruby Gems and then installing Rails from the command line, like this:

gem install rails --include-dependencies

and that was it.   In both Instant Rails and the native install I also install Rake and Capistrano.  Rake is a nice build utility that allows you to write your scripts in Ruby and Capistrano will help deploy your applications.  These are also installed using gem install. Replacing TextMate was  a lot easier than I thought it would be.  I found E-Text Editor.  It is in beta as I write this but is truly useful as-is.  You can see how much it looks like TextMate, including a ton of bundles. e-text All of this so far has been a great way to do Rails development on Windows, but wait it even gets better.  As I said already, I use Visual Studio 2005 all day.  I found a great VS.NET add-in called Ruby in Steel.  I have blogged about it before and have used it for a while and am spoiled by it. You can see the same Rails project loaded in Ruby in Steel.  Does it look like the familiar VS interface?  I hope so. RubyInSteel The best part of using Ruby in Steel is…Intellisense.  Can you tell I like Intellisense?  You can do debugging like you can in other VS languages as well.  These guys are doing a great job with bringing all the Rails goodness to Windows and Visual Studio in particular, they don’t get enough credit for their efforts.  Support is top-notch as well. The last piece I really needed to decide on was the database and it is a toss up between MySQL, PostgreSQL or SQLite.  It seems Rails has great support for all of the choices but MySQL has been supported the longest.  They all run on Windows so I don’t know if it matters that much, I chose MySQL. In case you want all the goodness of MVC but don’t want to write Ruby code then maybe checking out the CastleProject and MonoRail.  This is a full-blown MVC on Windows without using ASP.NET WebForms, which they incidentally have multiple ways to solve the same problem.  I for one, am checking them out now and writing some sample applications, they feel a lot like Rails.  I would take a look at one of their nightly builds which contain the latest and greatest.  The Windows install is a bit old at this point. Finally, I think today is a great time to start developing Rails application under Windows where you might be the most comfortable.  Please email me with other tips and suggestions. 

Technorati Tags: , , , , , , ,