#131: Rails 3

In this episode, Jason and Dan bring you up to speed on the recently released rails 3.

Links for this episode:

Enterprise Social Apps

With over 80,000 applications on Heroku, we are frequently asked what type of apps people are building. While there’s a wide range, one of the areas I’ve been most excited about is social apps. We have thousands of social applications around Twitter, Facebook, and other platforms. The Social App Workshop last month was proof of the interest with a sold out crowd of over 150 people filling a basement on a great summer Saturday.

Social platforms are sweeping enterprises as well. From internal communities for collaboration to external communities with millions of users, enterprises are finding social software essential to how they work. Today we’re announcing a partnership with the leader in this space – Jive Software. Over 3,000 leading companies, including over 25% of the Fortune 100, use the Jive platform to engage their employees, customers and partners.

If you are interested in building social applications for the enterprise and reaching millions of employees, we have a great opportunity for you. For the first time, Jive is opening up their platform to 3rd party application developers. Their new Jive Apps Market will make it easy for customers using the Jive platform to purchase cloud-based social app software. You’ll be able to deploy your applications to Heroku, and have companies from around the world view, purchase, and use your app within Jive. Jive is leading the way in bringing cloud social business applications into the enterprise, and we’re honored to be part of it.

To help you get started, Jive is holding their first ever Jive Apps Developer Event on September 16th at the San Francisco InterContinental Hotel. This is a great opportunity to both evaluate the size of the Jive Apps opportunity by mingling with enterprise customers as well as get the technical details from Jive engineers.

Jive and Heroku have teamed up to offer 10 free passes to the event. If you’d like to enter to win one of the passes, fill out this survey before Sept 2nd.

August 31, 2010: Bundled Mockingjays

Book Status

Editing the RSpec chapter, which I expect to be done today, it’s all done except for a couple of hard questions from the editor which last-night me decided to leave for this-morning me, so that last-night me could finish Mockingjay. Thanks, last-night me!

A Bundler Question

I’m not sure whether this is a feature-request or an I-don’t know what I’m doing request.

I’ve been using Bundler with a Rails 2.3.8 project, and it’s been working just fine for the most part, I like it. There’s one issue. The project also involves active development on a gem (so that business logic classes can be shared among multiple projects), and I’m not sure how to handle the case in Bundler.

The gem is a separate git repo. In development, the gem is specified in Bundler as a path, so that a developer can work on both without having to push the gem back to the central repo. In staging, though, the gem is specified via git based on the staging branch, and in production it’s specified via git based on the master branch.

What I would like to do is specify the same gem as having different sources in different groups, something like

group :production do
  "common_gem", :git => "git_repo"
end
group :development do
  "common_gem", :path => "dev path"
end

But bundler won’t let me do that because all it sees is the duplicate definition.

Has anybody had a similar issue? Right now, we’re resolving this via checkin scripts that ensure that various branches have the right gemfile when deployed. But it’s an awkward solution.

Mockingjay

Okay, I did finish it. I’m mostly amazed at how the Hunger Games books somehow became this year’s YA Book That It’s Okay For Grownup’s To Read. (It’s even got a multi-grownup book discussion on Slate). Trying to decide how I feel about the book, and this may not be the place to go on at length. Still, recommended — even with some flaws, the series is energetic and interesting.

Filed under: Bundler

RPCFN: Economics 101 (#13)

Ruby Programming Challenge For Newbies

RPCFN: Economics 101 (#13)

By Dr. Bruce Scharlau

About Dr. Bruce Scharlau

Dr. Bruce Scharlau In Dr. Bruce’s own words: “I’ve been using and teaching Ruby since trying out the cookbook example in the summer of 2006. As soon as I saw how much easier it all was with Ruby and Rails, I was hooked. I now try to do as much with Ruby as I can with my teaching and own work. It’s a joy to code with Ruby compared to using other languages, which don’t seem as intuitive by comparison. When I’m not busy working, then I try to spend time with the family, or get out sailing.”

Dr. Bruce has this to say about the challenge:

The challenge is useful for newbies as a way to extend their skills in a useful manner. They will learn how they solved the problem, and also gain from seeing how others solved the problem too. We all start from different places when we solve problems, so the ‘obvious’ solution to you, might not occur to someone else who has a different experience of Ruby. This is why it’s good to share examples and code together when possible too.

Prizes

  • The participant with the best Ruby solution (if there is a tie between answers, then the one who posted first will be the winner) will be awarded any one of PeepCode’s Ruby on Rails screencasts.
  • From the remaining working Ruby solutions, three participants would be selected randomly and each one would be awarded any one of Pragmatic’s The Ruby Object Model and Metaprogramming screencasts.

The four persons who win, can’t win again in the next immediate challenge but can still participate.

The Ruby Challenge

RPCFN

The Challenge

As a developer it helps to be able to understand a client’s perspective and to build suitable applications to help them in their field. This means knowing a bit about the world. We’ll help this background knowledge by doing looking at some economic data, and also testing our XML parsing skills.

The file cia-1996.xml is the data from the CIA World Factbook of 1996 in XML format. It has details about 260 countries across five continents. Your challenge, should you choose to accept it, is to uncover the following details buried within this file:

  1. What is the population of the country with the most people? Yes, we know it’s China, but just how many people lived there in 1996?
  2. What are the five countries with the highest inflation rates, and what were those rates in 1996?
  3. What are the six continents in the file and which countries belong to which continent? Can you also produce them in alphabetical order?

Once you’ve worked out how to do part (2), then you can do anything with this file; all you need is a bit of time. Knowing how to do (2) you could then do (3) without too much effort.

You can use any XML library. I used REXML as it’s already there if you have Ruby installed; so don’t need to worry about any gem installs. You may also want to look at how REXML uses XPath.

Submit your solution of your code, which includes a test file that answers the three questions.

How to Enter the Challenge

Read the Challenge Rules. By participating in this challenge, you agree to be bound by these Challenge Rules. It’s free and registration is optional. You can enter the challenge just by posting the following as a comment to this blog post:

  1. Your name:
  2. Country of Residence:
  3. GIST URL of your Solution (i.e. Ruby code) with explanation and / or test cases:
  4. Code works with Ruby 1.8 / 1.9 / Both:
  5. Email address (will not be published):
  6. Brief description of what you do (will not be published):

Note:

  • As soon as we receive your GIST URL, we will fork your submission. This means that your solution is frozen and accepted. Please be sure that is the solution you want, as it is now recorded in time and is the version that will be evaluated.
  • All solutions posted would be hidden to allow participants to come up with their own solutions.
  • You should post your entries before midnight of 27th Sept. 2010 (Indian Standard Time). No new solutions will be accepted from 28th Sept. onwards.
  • On 28th Sept. 2010 all the solutions will be thrown open for everyone to see and comment upon.
  • The winning entries will be announced on this blog before 30th Sept. 2010. The winners will be sent their prizes by email.

More details on the RPCFN?

Please refer to the RPCFN FAQ for answers to the following questions:

Donations

RPCFN is entirely financed by RubyLearning and sometimes sponsors, so if you enjoy solving Ruby problems and would like to give something back by helping with the running costs then any donations are gratefully received.

Click here to lend your support to: Support RubyLearning With Some Love and make a donation at www.pledgie.com !

Acknowledgements

Special thanks to:

  • Dr. Bruce Scharlau.
  • GitHub, for giving us access to a private repository on GitHub to store all the submitted solutions.
  • The RubyLearning team.

Questions?

Contact Satish Talim at satish [dot] talim [at] gmail.com OR if you have any doubts / questions about the challenge (the current problem statement), please post them as comments to this post and the author will reply asap.

The Participants

There are two categories of participants. Some are vying for the prizes and some are participating for the fun of it.

In the competition

  1. Dmytrii Nagirniak, Australia
  2. Kirill Shchepelin, Russia
  3. Lukasz Hanuszczak, Poland
  4. Rick DeNatale, USA
  5. David Lake, England
  6. Julio C. Villasante, Cuba
  7. Dan Wanek, USA
  8. Matthew Dahl, USA

Just for Fun

  1. Casimir Saternos, USA
  2. Paul McKibbin, U.K.

Previous Challenge

RPCFN: Cycle Tracks (#12) by David Griffiths.

Note: All the previous challenges, sponsors and winners can be seen on the Ruby Programming Challenge for Newbies page.

Update

  • The (#14) challenge by Joseph Wilk, U.K. is scheduled for Oct. 2010.

Technorati Tags: , , , , ,

Appreciate Rails 3 with charity

Rails 3.0 is a gift from all of us who’ve worked on it to anyone who wants to build something. If you like our gift, please show it by donating to the Rails 3.0 release charity: Charity:Water. We’ve started a campaign to raise $100,000 in the name of Rails 3.0, which will give 5,000 people access to clean water if we make it.

Charity:Water is a fantastic charity (and not just because they run on Rails!). You’d make everyone working on Rails proud by helping us reach our lofty goal.

Donations can be made at http://mycharitywater.org/rails3.

RubyDoc.info: Good Looking, Up-To-Date Ruby Documentation

RubyDoc.info is a new, automatically updated Ruby documentation site by Loren Segal and Nick Plante that builds upon their earlier success with rdoc.info (which we posted about in 2009). It’s powered by YARD, a tool that puts out great looking Ruby documentation (there’ll be more about YARD in a post later this week).

RubyDoc.info automatically generates documentation for all gems on rubygems.org (it updates its index once per day) but it does GitHub-hosted projects too. For RubyDoc.info to automatically update with documentation for your Ruby-related GitHub project, use the “Add Project” link on RubyDoc.info and then add http://rubydoc.info/checkout as one of your post-commit hook URLs in your repository’s settings – on each future commit, your latest documentation will be built on RubyDoc.info.

27 Video Presentations from RubyKaigi 2010

RubyKaigi is Japan’s “home” Ruby conference and the organizers have just put 27 videos from the RubyKaigi 2010 conference online. Unfortunately I can’t link to them individually as they’re embedded on a single page, so head over to rubykaigi.tdiary.net and check them out.

Presentation titles include: Ruby 2.0, Ruby API is Improved Unix API, Rocking The Enterprise With Ruby, Mapping the World with DataMapper, The Necessity and Implementation of Speedy Tests, A Metaprogramming Spell Book, Conflicts and Resolutions in Ruby and Rails, and User Experience for Library Designers.

Two caveats: 1) Be aware that some of the presentations are in Japanese (unsurprisingly) although most of the slides include English and, of course, any Ruby is still readable. There were also several English language speakers including Sarah Mei, Carl Lerche, and Jake Scruggs. 2) The player/hosting for the videos seems to be super slow. Give it time and they’ll load.

[jobs] Engine Yard are hiring! Did you know that Engine Yard – one of the biggest and brightest companies in the Ruby world – are hiring? They have Ruby Engineer and Ruby App Support Engineer positions open in San Francisco.

Aug 30, 2010: Rails 3 has landed

Top Story

As you probably know, both Rails 3 and Bundler went final over the weekend. The Rails 3 release notes are up, as well as extensive coverage on the Rails Guides page. I’ll also mention Jeremy McAnally’s Rails 3 Upgrade handbookhttp, and Gregg Pollack’s list of great Rails 3 documentation sources. And, just for the hell of it, here’s the post I wrote back when Rails 3 was first announced. Somehow, this is not the first Google result for the phrase “Merby Overlords”

In other news

I do mean to write about Obtiva’s Master Class with Alistair Cockburn, but that’s going to take way more concentration than I can muster this morning. For the moment, it’s enough to say that it was fun, interesting, and enlightening.

In honor, this link that Alistair tweeted over the weekend, the Half-Arsed Agile Manifesto. Anybody who doesn’t recognize themselves in that a little bit has never actually tried Agile.

Link Out

By the way, I loved doing the post based on search engine entries into the site… you’ll see that again, as it was relatively easy, kind of funny, and marginally useful, and that’s pretty much what I aspire to.

If you’re into programming abstractions and/or you want to learn about Lisp, Magnus Holm has an introduction to S-Expressions for Rubyists.

And if you are into crazy Ruby metaprogramming, Lance Pollard has a long look at instance_eval. It’s nice to see a metaprogramming example that’s actually motivated from a use case.

Highly prolific conference blogger Jake Scruggs was at RubyKaigi this week, here’s day one of his report. Day two. Day three.

Filed under: Obtiva, Rails 3, Ruby

#229 Polling for Changes

If you have frequently changing data on the server side, it’s helpful to automatically display this to the user as well. Here I show how to accomplish this with polling in jQuery.

#229 Polling for Changes

If you have frequently changing data on the server side, it’s helpful to automatically display this to the user as well. Here I show how to accomplish this with polling in jQuery.

Rails 3.0 Released (And 22 Free Videos To Bring You Up To Speed)

Rails 3.0 has been underway for a good two years, so it’s with immense pleasure that we can declare it’s finally here. We’ve brought the work of more than 1,600 contributors together to make everything better, faster, cleaner, and more beautiful.

David Heinemeier Hansson

DHH rings the bell and announces that Rails 3.0 (final) has been released after two years of determined effort by the Rails core team (and, significantly, Merb team members, since Rails 3.0 is heavily influenced by the Merb merger). Grab it now with gem install rails --version 3.0.0 or, if you’re in no rush, Rails 3.0.1 might come along within a week or two.

The Videos

DHH gives a quick roundup of some of Rails 3’s new features but like Emma Watson’s head PhotoShopped onto yet another naked body, it’s nothing you haven’t seen before. If you’re really fresh to Rails 3.0, though, Gregg does an admirable job of boiling everything down into a digestible format with his (free!) Dive Into Rails 3.0 screencast series:

Ryan Bates has also produced a fistful of his typically succinct but precise RailsCasts videos on a wide array of Rails 3.0 topics. Ryan always focuses on code and practicalities so these are a good place to start if you want to follow along and do some coding yourself:

If you don’t like videos, still follow the links, because there are links to the ASCIIcasts regular HTML versions of the Railscasts videos. These are regular blog posts that you can follow at your own pace.

Or some books

Michael Hartl’s Rails Tutorial book is the #1 (and only, in my opinion) place to start when it comes to books about learning Rails 3.0. Not only is it available to read for free online, but you can buy a well formatted PDF too. It’s an amazing piece of work and, unusually, walks you through building a Rails app from start to finish with testing. If you want to just read one book/site and feel like a Rails 3.0 master by the end of it, pick RailsTutorial.org.

If you speak German, though, check out this “Ruby on Rails 3” book by Michael Voigt and Stefan Tennigkeit. It’s one of the first Rails 3.0 specific books to hit the presses.

Or just dive into some code

If you want to just “get started” and check out a working Rails 3.0 application, try Daniel Kehoe’s Rails3-Subdomain-Devise app. It’s a basic Rails 3.0 app that demonstrates using the Devise authentication system, as well as custom subdomain access. Not just that, but Daniel has put together a walkthrough of how the app works and how it was put together.

Building an Object Mapper: Override-able Accessors

There are several things I have learned building object mappers that I now take for granted. Last week while pairing with Jason, I was explaining a trick and he said I should blog about it, so here goes nothing.

Let’s say you are building a new object mapper named TacoMapper. A sensible place to start is with attribute accessors. One other thing to note is that we don’t care about old news, so we won’t support Rails 2 in any fashion. Deciding this, we can take advantage of ActiveModel and new features in ActiveSupport.

First Goal

First, let’s think about API. Our first goal will be to make the following work:

class User
  include TacoMapper
  attribute :email
end

user = User.new
user.email = 'John@Doe.com'
puts user.email # "John@Doe.com"

First Solution

The first thing we need is a class method named attribute.

require 'active_model'
require 'active_support/all'

module TacoMapper
  extend ActiveSupport::Concern

  module ClassMethods
    def attribute(name)
      attr_accessor(name)
    end
  end
end

class User
  include TacoMapper
  attribute :email
end

user = User.new
user.email = 'John@Doe.com'
puts user.email # "John@Doe.com"

ActiveSupport::Concern is a handy little ditty that does a lot out of the box. In our case, it will automatically call extend(ClassMethods) and add our attribute class method whenever our TacoMapper module gets included. With just a tiny bit of code, we have met our first goal.

Second Goal

Now, I am going to throw a kink in the mix. The goal of this post is to create override-able accessors. Let’s say we want to override the email writer method and make sure that we always get lowercase emails. If we override our attribute accessors right now, we have to set the instance variable for things to work and we get no benefit from TacoMapper.

require 'active_model'
require 'active_support/all'

module TacoMapper
  extend ActiveSupport::Concern

  module ClassMethods
    def attribute(name)
      attr_accessor(name)
    end
  end
end

class User
  include TacoMapper
  attribute :email

  def email=(value)
    @email = value.to_s.downcase
  end
end

user = User.new
user.email = 'John@Doe.com'
puts user.email # "john@doe.com"

In this simple example, that might be ok. But what if other things were in the mix, like dirty tracking, typecasting, etc.? Those other things would immediately stop working. Would it not be nice if we could just override our accessor and call super to get all the normal functionality of TacoMapper? I am glad you agree.

Second Solution

If you haven’t yet, you might want to read Lookin’ on Up…To the East Side, a post I wrote on how Ruby’s method lookups work. In it, I explain that if you include a module, you can override methods that were in the module and call super. We’ll do the same in TacoMapper so we can make things a bit more robust.

require 'active_model'
require 'active_support/all'

module TacoMapper
  extend ActiveSupport::Concern

  module ClassMethods
    def attribute_accessors_module
      @attribute_accessors_module ||= Module.new.tap { |mod| include(mod) }
    end

    def attribute(name)
      attribute_accessors_module.module_eval <<-CODE
        def #{name}
          @#{name}
        end

        def #{name}=(value)
          @#{name} = value
        end
      CODE
    end
  end
end

class User
  include TacoMapper
  attribute :email

  def email=(value)
    super(value.to_s.downcase)
  end
end

user = User.new
user.email = 'John@Doe.com'
puts user.email # "john@doe.com"

Note that we get the same result as the previous example, except that now we can just call super and still take advantage of all the loveliness that TacoMapper will eventually provide. We changed a couple of key things, so lets cover the differences in detail.

First, we created a method (attribute_accessors_module) that returns a memoized module and includes it in the current class. No matter how many calls you make to this method, it will return the first module we created and it will only be included once, since we memoized it (||=).

Second, since we have a module and it is included in our class, all we have to do is module_eval our accessor methods into it. This is what is happening in the attribute method.

Third, instead of setting the email instance variable in the email= method, we just call super, which will call the method we module_eval’d into our accessors module.

Pretty sweet, eh?

Third Solution

We could stop there, but we said we were going to use ActiveModel a bit, right? ActiveModel has a module for attribute accessors that does the same thing as above and a bit more (although a bit confusing).

require 'set'
require 'active_model'
require 'active_support/all'

module TacoMapper
  extend ActiveSupport::Concern
  include ActiveModel::AttributeMethods

  included do
    attribute_method_suffix('', '=')
  end

  module ClassMethods
    def attributes
      @attributes ||= Set.new
    end

    def attribute(name)
      attributes << name.to_s
    end
  end

  module InstanceMethods
    def attribute(key)
      instance_variable_get("@#{key}")
    end

    def attribute=(key, value)
      instance_variable_set("@#{key}", value)
    end

    def attributes
      self.class.attributes
    end
  end
end

class User
  include TacoMapper
  attribute :email

  def email=(value)
    super(value.to_s.downcase)
  end
end

user = User.new
user.email = 'John@Doe.com'
puts user.email # "john@doe.com"

Note that again, we get the same result and that we are using super as before. So what changed this time?

First, we included ActiveModel::AttributeMethods. We then took advantage of the attribute_method_suffix method it provides to declare that we would have a reader ('') and a writer ('='). Now all our attribute class method has to do is add the attribute to the set of attributes.

Lastly, we define methods that implement the suffix methods we defined (attribute and attribute=). Note that we also define the attributes instance method so that ActiveModel knows when it is dealing with one of our attributes. Now, it takes only a few more lines of code to add a boolean presence method.

require 'set'
require 'active_model'
require 'active_support/all'

module TacoMapper
  extend ActiveSupport::Concern
  include ActiveModel::AttributeMethods

  included do
    attribute_method_suffix('', '=', '?')
  end

  module ClassMethods
    def attributes
      @attributes ||= Set.new
    end

    def attribute(name)
      attributes << name.to_s
    end
  end

  module InstanceMethods
    def attribute(key)
      instance_variable_get("@#{key}")
    end

    def attribute=(key, value)
      instance_variable_set("@#{key}", value)
    end

    def attribute?(key)
      instance_variable_get("@#{key}").present?
    end

    def attributes
      self.class.attributes
    end
  end
end

class User
  include TacoMapper
  attribute :email

  def email=(value)
    super(value.to_s.downcase)
  end
end

user = User.new
puts user.email? # false
user.email = 'John@Doe.com'
puts user.email? # true

Using ActiveModel like this makes adding things like dirty tracking take a few minutes instead of a few hours. That said, the main point of this post is how the internals of ActiveModel actually work and how you can do it on your own if you so choose.

For those of you that are MongoMapper users, it has the same functionality built in though in a not as elegant way (which I will be updating soon). Also, your accessors are not used when loading things from the database, as that is handled internally. This means you can make your public accessors do whatever you want and it will not foobar the loading of your documents.

Hope this helps others trying to grok ActiveModel or build your own object mapper. If you enjoyed this post and would like to learn more about building an object mapper, let me know with a comment and I will try to round up a few more posts on the topic.

Rails 3.0: It’s ready!

Rails 3.0 has been underway for a good two years, so it’s with immense pleasure that we can declare it’s finally here. We’ve brought the work of more than 1,600 contributors together to make everything better, faster, cleaner, and more beautiful.

This third generation of Rails has seen thousands of commits, so picking what to highlight was always going to be tough and incomplete. But here’s a choice selection of major changes for Rails 3:

New Active Record query engine
Active Record has adopted the ARel query engine to make scopes and queries more consistent and composable. This makes it much easier to build complex queries over several iterations. We also delay the actual execution of the query until it’s needed. Here’s a simple example:

users = User.where(:name => "david").limit(20)
users = users.where("age > 29")

# SELECT * FROM users 
# WHERE name = "david" AND age > 29 
# ORDER BY name
# LIMIT 20
users.order(:name).each { |user| puts user.name }

Read more in new Active Record guide and watch the Dive into Rails 3: ARel video.

New router for Action Controller
When we switched to a REST-based approach for controllers in Rails 2, we patched on the syntax to the existing router while we were waiting to see if the experiment panned out.

It did and for Rails 3 we’ve gone back and revamped the syntax completely to favor the REST style with less noise and more flexibility:

resources :people do
  resource :avatar

  collection do
    get :winners, :losers
  end
end

# /sd34fgh/rooms
scope ':token', :token => /\w{5,5}/ do
  resources :rooms
end

# /descriptions
# /pl/descriptions
# /en/descriptions
scope '(:locale)', :locale => /en|pl/ do
  resources :descriptions
  root :to => 'projects#index'
end

Read more in the new routing guide.

New Action Mailer
Action Mailer was born with a split-personality of half model, half controller. In Rails 3, we’ve made the choice to make it all controller. This means that the feel and functionality will be much closer to Action Controller and in fact they now share a bunch of underlying code. Here’s a taste of what it looks like now:

class Notifier < ActionMailer::Base
  default :from =>
    "Highrise <system@#{APPLICATION_DOMAIN}>" 

  def new_project(digest, project, person)
    @digest, @project, @person = digest, project, person

    attachments['digest.pdf'] = digest.to_pdf
    attachments['logo.jpg']   = File.read(project.logo_path)

    mail(
      :subject => "Your digest for #{project.name}",
      :to => person.email_address_with_name
    ) do |format|
      format.text { render :text => "Something texty" }
      format.html { render :text => "Something <i>texty</i>" }
    end
  end
end

The new Action Mailer is built on top of the new Mail gem as well. Say goodbye to TMail headaches.

Read more in new Action Mailer guide.

Manage dependencies with Bundler
Managing all the dependencies of a Rails application has long been a hassle of patchworks. We had config.gem, Capistrano externals, custom rake setup tasks, and other incomplete solutions.

Bundler cleans all that up and allows you to specify the libraries, frameworks, and plugins that your application depends on. All Rails 3 applications are born with a Gemfile to control it all. See more on the Bundler site.

XSS protection by default
The internet is a scary place and Rails 3 is watching out for you by default. We’ve had CRSF protection with form signing for a while and SQL-injection protection since the beginning, but Rails 3 ups the anté with XSS protection as well (hat tip to Django for convincing us).

See the Railscast on XSS video and the Dive into Rails 3: Cross-site scripting video for more.

Say goodbye to encoding issues
If you browse the Internet with any frequency, you will likely encounter the � character. This problem is extremely pervasive, and is caused by mixing and matching content with different encodings.

In a system like Rails, content comes from the database, your templates, your source files, and from the user. Ruby 1.9 gives us the raw tools to eliminate these problems, and in combination with Rails 3, � should be a thing of the past in Rails applications. Never struggle with corrupted data pasted by a user from Microsoft Word again!

Active Model: Validations, callbacks, etc for all models
We’ve extracted quite a bit of commonly requested Active Record components into the new Active Model framework. This allows an ORM like Mongoid to use Active Record’s validations, callbacks, serialization, and i18n support.

Additionally, in the rewrite of Action Controller, we removed any direct references to Active Record, defining a clean, simple API that ORMs can implement. If you use an API-compliant ORM (like DataMapper, Sequel, or Mongoid), you will be able to use features like form_for, link_to and redirect_to with objects from those ORMs without any additional work.

Official plugin APIs
We also rewrote Railties with the express goal of using the new plugin API for all Rails frameworks like Active Record and Action Mailer. This means that Rails plugins like the ones for DataMapper and RSpec have access to all of the integration as the built-in support for Active Record and Test::Unit.

The new Railtie API makes it possible to modify the built-in generators, add rake tasks, configure default Rails options, and specify code to run as early, or as late as you need. Rails plugins like Devise were able to add much better integration in the Rails 3 version of their plugin. Expect to see a lot more of that in the months ahead.

Rewritten internals
We rewrote the internals of Action Pack and Railties, making them much more flexible and easier to extend. Instead of a single monolithic ActionController::Base, Rails 3 exposes a number of modules, each with defined APIs, that you can mix and match to create special-purpose controllers for your own use. Both Action Mailer in Rails and the Cells project make heavy use of this new functionality.

You can also take a look a this blog post by Yehuda (from last year) to see how the new architecture makes it easy to implement Django-style generic actions in Rails by leveraging Rack and ActionController::Metal.

The Rails generator system is got a revamp as well. Instead of monolithic generators that know about all of the Rails frameworks, each generator calls a series of hooks, such as :test_framework and :orm, that plugins can register handlers for. This means that generating a scaffold when using rSpec, DataMapper and Haml will generate a scaffold customized for those plugins.

Agnosticism with jQuery, rSpec, and Data Mapper
The rewritten internals and the new plugin APIs have brought true agnosticism to Rails 3 for all components of the framework. Prefer DataMapper to Active Record? No problem. Want to use jQuery instead of Prototype? Go ahead. Eager to test with rSpec instead of test/unit? You got it.

It’s never been easier to Have It Your Way™ with Rails 3. And at the same time, we’ve made that happen without making using the excellent default stack any more complicated.

Documentation
Rails 3 has had a long development cycle and while that might have lead to some impatience, it has also given book and tutorial authors a chance to catch up and be ready. There’s a wealth of great Rails 3 documentation available already and more is coming shortly.

The Agile Web Development with Rails 4th Ed book is almost ready and there are plenty more books coming. Check out all the new guides, the new official videos, new Railscasts, and a new tutorial. See the recent recap of documentation sources for more.

Installation
gem install rails --version 3.0.0.

We also have a Rails v3.0.0 tag and a 3-0-stable branch.

Rails 3.0 has been designed to work with Ruby 1.8.7, Ruby 1.9.2, and JRuby 1.5.2+.

Gratitude and next steps
I’m personally incredibly proud of this release. I’ve been working on Rails for more than 7 years and the quality of the framework we have today is just astounding. This is only possible as a community effort and Rails 3 has seen so many incredible developers step up and help make this our best release ever (wink). Many thanks to all of you.

We’ll continue to develop Rails 3.0 with fixes and tweaks via the stable branch and Rails 3.1 is already cooking on master.

UPDATE: We’re raising money for Charity:Water in the name of Rails 3.0. Please donate and help us bring clean water to 5,000 people in the name of the Rails community.

EuRuKo 2010: Summaries, Videos, and Photos from Europe’s Ruby Conference

EuRuKo is the brand of Europe’s principal Ruby conference series and EuRuKo 2010 took place in late May. Why, then, am I posting about it in August? First, I’m a strong supporter of EuRuKo and promised to post a roundup of the event here. Secondly, it turns out it took a while for the videos to all be uploaded 😉 Third, I’ve taken my time in getting round to it. Nonetheless, there are some amazing presentations you can watch and they’re still fewer than three months out of date!

One of the event’s organizers, Ela Madej, gives a summary:

European Ruby Conference 2010 is now well over and the Berlin EuRuKo 2011 team are surely working on their opening song for the next year. Yes, we all know they sing well – their uber-strong German vocal was nothing but adorable.

Despite the flooding and changing the conference venue just one week before the event, EuRuKo was great! It was filled with fantastic talks and Rubyists from all over the planet. Here are some numbers: around 121 Poles (less than half of all 280 attendees), at least 40 Germans, Rubyists from Japan, Austria, Spain, UK, Switzerland, Uruguay, USA, Cuba, Slovakia, Czech Republic, Slovenia, Croatia, Estonia, The Netherlands, Latvia, Italy, France, Belgium, Brasil and more.

For everyone who missed the event, the videos from the conference are on Vimeo. There is also a great summary of the talks for Day One and
Day Two. Here are the links to EuRuKo official photos on Flickr for Day One and Day Two also.

Ela Madej

While there are 37 videos on offer, some standouts include:

EuRuKo is supported by not only by Rubyists paying to attend but by quite a few sponsors, with 2010’s event no exception. The organizers asked me to specially thank their biggest sponsor Novelys – a team of French Ruby on Rails experts. On top of that, EuRuKo’s afterparty sponsors were Applicake and Lunar Logic Polska, two Ruby development teams from Poland. Finally, 16 micro sponsors helped out too.

I’ve been a keen supporter of EuRuKo since the first event so a big thanks to all of the sponsors and attendees for supporting Ruby’s principal Ruby conference. Now, go enjoy those videos.

Rails Has Great Documentation

To this day I still hear people complain that Rails has poor documentation. From where I’m sitting this seems far from the truth. Let me lay out the evidence piece by piece:


RailsTutorial.org

To learn Rails from scratch Michael Hartl recently finished his book Ruby on Rails Tutorial: Learn Rails by Example. The book teaches Rails 3 from the ground up and it’s available for FREE online. If you’d rather have a PDF or a book you can grab that as well (and he’s even working on some screencasts).

The source for the finalized book will be pushed to GitHub and released under a Creative Commons License shortly after Rails 3 is done. If you’d like to help translate the book to your language of choice, feel free to contact Michael and he’ll get in touch when it’s time to make it happen.

Rails Guides

If you’re not a Rails newbie don’t forget about the Rails Guides, which have been updated for Rails 3.

Rails API Docs

There are two main websites I use to do API lookups. The first is Rails Searchable API Doc, which has online and offline searchable documentation. The second is APIdock which is online only, but has the ability to comment and easily compare different versions of documentation.

Rails 3 Free Screencasts

If you’re more of a visual learner (like me) then there are plenty of free screencasts to teach you about Rails 3. About 2 months ago I produced the Rails 3 Screencasts, which will get you started.

Ryan Bates has also produced an incredible amount of Rails 3 screencasts over on Railscasts.com. Ryan has been producing Railscasts for over 3 1/2 years, isn’t that crazy?

There’s also a few good free screencasts over on Teach me to Code by Charles Max Wood.

Keeping on the Edge

If you find yourself wondering how to keep up with all of the newest features / libraries for Rails 3, both the Ruby5 Podcast and the Ruby Show are going strong. Don’t listen to audio? It doesn’t matter, just subscribe to the Ruby5 RSS feed and get links with descriptions to all the newest libraries, tutorials, and more. You might also want to checkout Peter Cooper’s new Ruby Weekly, a Ruby email newsletter.

Need to upgrade a big app to Rails 3?

Jeremy McAnally’s Rails 3 Upgrade Handbook PDF is just $12. There’s also a few paid screencasts for the upgrade over on Thinkcode.tv and BDDCasts.

Need a Book?

There’s a bunch of books that will be coming out after the release, most of which you can start reading now. The Rails 3 Way by Obie Fernandez, Rails 3 In Action by Ryan Bigg and Yehuda Katz, Beginning Rails by Cloves Carneiro Jr and Rida Al Barazi, and of course the Agile Web Development with Rails:fourth edition by Sam Ruby, Dave Thomas, and David Heinemeier Hansson.

In conclusion

No more complaining about lack of good documentation! Seriously. If you want even more Rails 3 content, check out the blog post by Kevin Faustino on 34 Ruby on Rails 3 resources to get you started.

Aug 27, 2010: Seek and You Shall Find

I always feel a little bad for the people who come to this site via search. There aren’t very many of them, mind you, but it always feels like they are destined to be disappointed if they are coming here to actually get information.

In that sprit, I’m going to respond to some of the search terms that WordPress says have brought people to this site in the last 48 hours. Better late then never, right?

Is there anything better than Rubymine

how to install plugin with rubymine

Funny you should ask because I’ve been voluntarily using RubyMine over TextMate on my current project (the Cucumber support sealed the deal). It’s not perfect, and it’s not as good a pure editor as TextMate, let alone Vim. But I come to form the idea that the things that RubyMine is good at — mostly project navigation, and easy running of tests — are things I do all the time. The things that Vim or TextMate are better at — helping me put text on the page more quickly — well, it’s not like I don’t type all the time, but the advanced features of those editors are things I need less frequently. So RubyMine works best for me right now, despite some flaws that still remain.

As for plugins, I think you need to start at the preference screen.

Ackmate no results

Have you tried adding the file type you are interested in to the options field or an .ackrc file, a la http://wiki.github.com/protocool/AckMate/

Moving from authlogic to devise

Recommended. Well, starting a new project with devise. I’m not sure I’d mess with a working project.

Scrivener Dropbox Support

As far as I can tell, you’re out of luck for a simple solution until Scrivener 2.0 comes out, at least if you want to be able to edit the files on Dropbox outside of Scrivener.

Rails 3 Html5

Yes.

Jasmine Rails

rspc testing javascript

jasmine docs testing

jasmine rails how to

Seems like there’s some interest here. Mostly I just wish everything would sit still for a few months so I could finish the book. But what with Relevance saying they aren’t supporting Blue Ridge in favor of Jasmine, I’m pretty much forced to try to redo the chapter in Jasmine. Which looks nice, but has not quite progressed to the documentation writing phase, as far as I can tell. Still, I expect this to be Beta 8 of the book, sometime in early September.

Jruby auth authlogic

Hmm… never tried it, but I think it’ll work

capybara csv test

Not sure you need capybara to test CSV output, but this question actually might have been answered by a post on this blog. Hurray.

how to get bullet points in pages ipad

Press the “i” button in the toolbar to get the inspector, then select list from the nav bar in the inspector window.

In a related story, Apple snuck in an iWork update yesterday that adds output to ePub to Mac Pages suitable for the iBooks store, along with a document that can serve as a template to make things look right — the ePub support looks for particular paragraph styles. Nice to see that, especially nice to see that without having to pay for an upgrade.

rspec testing css

I think in an RSpec view test, you’re expected to use the Webrat have_selector matcher these days.

rails text editor ipad

Haven’t found anything I like specifically for coding yet, but Droptext is okay for general text. Still looking for an editor with programmer style tools that works with Dropbox.

chronic rails 3

As far as I know, they work together fine.

rails testing

rails unit shoulda

Hey, I have a book you might be interested in…

Filed under: Uncategorized

August 26, 2010: Some New Stuff

Book Status

RSpec chapter draft handed in to edit. It’s going to need a better conclusion. A lot changed in this one, relative to the Lulu version — this is probably the chapter most affected by my own personal experience since it’s original version.

Links

Haven’t done a link set in a while, this is going to be kind of random.

Still seats available for both WindyCityRails in general, and for my tutorial in specific. But the sponsor list has filled up.

Motorola bought 280 North, best known for their Cappuccino JavaScript framework, and the 280 Slides application. Apparently, Motorola plans to use them to make web apps aimed at Android devices. Should be an interesting culture clash.

I’ve been looking through the Rails 3 unobtrusive JavaScript stuff trying to figure out new practices. The Trevor Turk blog has a code snippet for setting up a form that submits when a checkbox is clicked. Like it. Love to see more examples like this, it really shows how clean the Rails 3 structures will be.

Ever wish the Ruby Date and DateTime classes were faster? Course you have. Here’s home_run, a C implementation of the Date and DateTime classes that claims a 20 – 200 time speedup. The Readme page shows how to use the home_run classes instead of the standard ones, if you are feeling adventurous.

I love stories of tracking down obscure bugs, and Yehuda Katz has a great one about bundler, rvm, and various shell interactions. Debugging is maybe the important skill, so watch an expert’s process at work.

Speaking of rvm and it’s awesomeness, here’s a quick guide to putting rvm, bundler, and passenger together on a Rails deploy.

Here’s a little test snippet to solve the problem of how to test an abstract controller by adding a small controller in the test page and creating a route for it.

Filed under: JavaScript, Ruby, rvm, WindyCityRails, Yehuda

Pragmatic Guide series: Pragmatic Guide to Git

New Pragmatic Guide series: Pragmatic Guide to Git now in beta

Ruby Weekly: A Ruby E-mail Newsletter from Ruby Inside

It’s time to unveil my latest project: Ruby Weekly, a once-weekly e-mail roundup of 10-20 Ruby related links with a few sentences on each. It’s had a brief alpha testing period and it’s now ready to roll.

Click here to subscribe to Ruby Weekly – it’s a one click process. It’s also ultra simple to unsubscribe if it’s not eventually to your taste.

As well as featuring links and (very) brief summaries, the weekly e-mail will also occasionally include new event, book, and job announcements and, if something significant is going on in Rubyland, a few paragraphs of editorial. The aim, though, is to keep the e-mail reasonably brief, in a plain format, and, above all, useful.

There’s been a renaissance in e-mail newsletters in the last year or two and it seemed, to me, to be a great way to get programming related news. E-mail is not to everyone’s taste (Ruby Inside will be staying as-is!) but if you want to avoid daily distraction and get a summary just once a week, it’s an alternative to reloading Twitter or Google Reader every day. The popularity of the Ruby5 podcast proves there’s an appetite for Ruby news in different media (and if you prefer audio, check them out).

Ruby Weekly goes out once a week on Thursdays, so if you subscribe within the next 16 hours or so, you’ll get this Thursday’s edition (issue #4).

#130: Mailing List Edition

In this episode, Jason and Dan go over the latest releases of Ruby and Rails. Kudos to the Rails team for releasing before this episode aired. Shame on the Ruby team for releasing right after the last episode of The Ruby Show aired.

Links for this episode: