You are currently browsing the tag archive for the 'rails' tag.
I’ve got two major announcements to make affecting my professional life this month. Today the first of them is ready to go live: I’ve accepted a position with the new Ruby on Rails Activists team. Probably the easiest way to explain what that means is to quote from the blog entry announcing our existence:
The mission of the Rails Activists is to empower and support the worldwide network of Ruby on Rails users. We do this by publicizing Rails, making adoption easier, and enhancing developer support.
Generally speaking, the Activists will be working alongside the Rails Core team, with the intent of helping publicize Rails and pull together efforts from all parts of the Rails ecosystem. We have a lot of ideas about what this could translate to in terms of concrete initiatives, but I’d like to emphasize that we’re here to support the rest of the community, not to direct it. If you want to get involved with promoting Rails and improving things, feel free to contact any one of us to discuss how we can help out. I’m easy to find:
It’s also important to note that although there are four of us who are now in some sense authorized to speak on behalf of Rails, this does not mean that everything we say is an Official Statement. We all have our own businesses and blogs and so on, and we have lives beyond Rails activism, shocking though that may be. For example, just because I link something on this weblog doesn’t mean it’s gotten some official stamp of approval.
We also intend for the communication to flow in as many directions as possible - one of our roles is to serve as ombudsmen for the Rails community. If for any reason you’re feeling frustrated in an attempt to talk to the core team (though personally, I’ve found them very approachable), do get in touch to see if we can help.
As some of you have probably guessed, the new team owes something to the much-discussed merger of Rails and Merb. In addition to picking up the best ideas from Merb, Rails is also working on picking up some of the best patterns from the Merb community. Just as Rails isn’t throwing out all of its old code to become a copy of Merb, we’re not throwing out all of our old activities (such as the Rails Guides) to copy Merb’s ecosystem. What we are doing is trying to incorporate some of the energy from the combined communities to revitalize both of them as they become one.
So stay tuned to see what initiatives emerge from this new group and its interactions with the wider Rails community. If you have any questions, I’ll be more than happy to address them in comments here or privately.
Welcome to 2009. Now I’m off to fix some date-related bugs.
2008 was a good year for me professionally. Here’s hoping that 2009 shapes up even better.
- Ubiquity 0.1.3 - Just out, the new version of the command line for Firefox. Like TextMate, this is one of those applications that I know I’m barely scratching the surface of.
- What good is a flexible paperclip? - Thoughtbot’s file attachment plugin is getting some overhaul.
- Espresso Public Beta - MacRabbit’s new web development environment. I need to find time to play with this, too.
- [ANN] Ruby 1.9.1 RC1 is released‘ - I’m responsible for this, you know: it happened minutes after I managed to get 1.9.1-pre2 installed.
- Learnivore! - Aggregation portal for Ruby and related screencasts.
I spent a lot of yesterday deep in the Rails source, trying to figure out why some tests weren’t passing. No final conclusion but I think I’m on the right track.
Over the years, ActionController::Base#render has grown quite a few options:
render :action => "edit"
render :template => "products/show"
render :file => "/u/apps/other/warning.html"
render :nothing => true
render :inline => "<% @product.name %>"
render :update {|p| p.replace_html "A", "Error!"}
render :text => "OK"
render :json => @product
render :xml => @product
render :js => "alert('error!');"
Those options will still be in Rails 2.3, but the first three have a simpler alternative now:
render "edit" render "products/show" render "/u/apps/other/warning.html"
Rails will figure out whether you’re rendering an action, template, or file, and do the right thing. In addition, if you like symbols, you can render an action via a symbol:
render :edit
Last one of these before my tiny Christmas break.
Things may slow down a bit for the holidays…but for me, they’re still cooking right along.
QA and documentation are on my mind this morning. I need to remember the lesson that a PM can’t spend all their time coding.
Spent part of yesterday learning more than I really want to know about Apache logging. Perhaps I should raise our eldest to be a sysadmin.
Off to a new week, packed with promise…and deadlines…
Round numbers of these things always make me happy.
I’ve gone back to big pieces of paper (actually giant Post-It Notes) for ERDs. Feels very satisfying in the absence of acres of whiteboards.
Does anyone actually like end of the year bookkeeping?
It’s another new week, full of hope.
Ever write code like this in Rails?
if File.exists?(File.join(RAILS_ROOT, 'config', 's3.yml')) has_attached_file :s3_image, :storage => :s3, :s3_credentials => File.join(RAILS_ROOT, 'config', 's3.yml') end
That particular snippet is from an application that optionally uses Amazon S3 to store images, if there is a configuration file for S3 supplied in the deployment. Well, you can clean that up a bit. First, although the RAILS_ROOT constant is still supported, we’ve had the prettier-looking Rails.root for months. Second, as of a recent commit to edge rails, Rails.root returns a Pathname object, so it directly supports the join method. Hence, the code snippet above can now be:
if File.exists?(Rails.root.join('config', 's3.yml'))
has_attached_file :s3_image,
:storage => :s3,
:s3_credentials => Rails.root.join('config', 's3.yml')
end
A tiny improvement, but of such tiny improvements are a pleasant framework made.
Has anyone seen my missing productivity?
Doesn’t feel like I have enough projects to justify the amount of busy I am. Not sure what that’s about.
Win some, lose some: good new client onboard yesterday, several older clients delinquent in their payments. The joy of freelancing.
Sometimes distributed team project management is very trying.
Somehow I survived November. Here’s hoping December will be less stressful.
If you develop Rails applications, you’re probably used to seeing this sort of thing in your log files:
Really, the only important thing there (as far as helping me find the source of the error) is the very first line of the backtrace: ActiveRecord::StatementInvalid (SQLite3::SQLException: no such table: posts: SELECT * FROM "posts" ):. But Rails throws in another 55 lines of backtrace information, just in case I have exposed a bug somewhere in Active Record or Action Pack or the dispatcher or Mongrel or Rack or even the initial script/server command. In most cases, that’s just noise.
Rails 2.3 (inspired by Thoughtbot’s Quiet Backtrace plugin) is smart enough to just shut up about the parts I don’t care. Here’s the default Rails 2.3 log in the same situation:
Processing PostsController#index (for 127.0.0.1 at 2008-11-29 08:12:31) [GET] Post Load (0.0ms) SQLite3::SQLException: no such table: posts: SELECT * FROM "posts" ActiveRecord::StatementInvalid (SQLite3::SQLException: no such table: posts: SELECT * FROM "posts" ): /app/controllers/posts_controller.rb:5:in `index' Rendered /Users/mike/scratch/blog23/vendor/rails/actionpack/lib/action_controller/templates/rescues/_trace (18.0ms) Rendered /Users/mike/scratch/blog23/vendor/rails/actionpack/lib/action_controller/templates/rescues/_request_and_response (0.6ms) Rendering /Users/mike/scratch/blog23/vendor/rails/actionpack/lib/action_controller/templates/rescues/layout.erb (internal_server_error) Completed in 34ms (DB: 0) | 500 Internal Server Error [http://localhost/posts]
Much nicer. Rails uses a combination of silencers (which just throw away lines matching a particular pattern) and filters (which make regex-based substitutions) to clean up the backtrace.
The guts of the backtrace cleaner are in ActiveSupport::BacktraceCleaner, letting you set up your own cleaners. Most of us, though, will be using the default backtrace cleaner that Rails spins up during initialization, Rails::BacktraceCleaner. Rails adds a variety of filters and silencers “out of the box”:
ERB_METHOD_SIG = /:in `_run_erb_.*/
VENDOR_DIRS = %w( vendor/plugins vendor/gems vendor/rails )
SERVER_DIRS = %w( lib/mongrel bin/mongrel lib/rack )
RAILS_NOISE = %w( script/server )
RUBY_NOISE = %w( rubygems/custom_require benchmark.rb )
ALL_NOISE = VENDOR_DIRS + SERVER_DIRS + RAILS_NOISE + RUBY_NOISE
def initialize
super
add_filter { |line| line.sub(RAILS_ROOT, '') }
add_filter { |line| line.sub(ERB_METHOD_SIG, '') }
add_filter { |line| line.sub('./', '/') } # for tests
add_silencer { |line| ALL_NOISE.any? { |dir| line.include?(dir) } }
end
So, by default, Rails will throw away all the messages from the vendor folders and the servers, among other things. Naturally, you can change these defaults. Rails 2.3 adds a config/initializers/backtrace_silencers.rb file to your application. You can add your own silencers or filters in this file:
Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ }
You can also tell Rails to remove the default silencers if you’re worried that you have uncovered a deeper bug:
Rails.backtrace_cleaner.remove_silencers!
Because the silencer is set up during the initialization process, you need to restart the server if you make any changes to it.
Currently in edge, the in-browser backtrace pages that you get in development mode show the full backtrace, not the silenced one.
Hopefully I will shake off the post-turkey stupor and write some code today.
I’d forgotten how fun trying to pull all the pieces together on a last-minute high-pressure project could be.
I recently hit a situation where I needed to sort an array of ActiveRecord objects on a particular attribute. The catch was that in this case the array started out with the results of a find operation - but then it had a bunch more transient objects added to it that weren’t part of the database. Fortunately the Array#sort method makes short work of this. Given an array a of objects with an entry_date attribute:
a.sort! {|x,y| x.entry_date <=> y.entry_date}
Because this was the only sort I needed on this particular model, I decided to push the operation right down into the model:
class Receipt < ActiveRecord::Base
def <=> (other)
entry_date <=> other.entry_date
end
end
Then the sort is much simpler:
a.sort!
Note that this technique only makes sense if your array isn’t coming straight from the database. If you are retrieving records from the database, you’re better off including an :order clause in your finder to let the database do the sorting.
Too busy to do more than post a couple of links, alas.
This month is definitely ending with a bang.
There has been an astounding amount of invective and discussion over a recent addition to Rails. Briefly, if you have an array in Rails, you can now use ordinal numbers to get at the first ten members through aliases such as Array#second, Array#third, and so on. Some people are concerned about code bloat, some are concerned about lack of elegance, and DHH’s judgment in writing this bit of code has been seriously challenged.
Well, I’m not happy either - because the changes don’t go far enough. Let’s add one more method to Array and be done with it:
Class Array
def by_ordinal(pos)
self[pos.to_i - 1]
end
end
With this simple addition, you can refer to Array.by_ordinal("3rd"), Array.by_ordinal("21st"), or even Array.by_ordinal("407th"). As a bonus, the naming of the individual members is consistent with Rails’ Inflector#ordinalize method. Please join me in pushing for this to be included in Rails core.
Some days I am amazed that any software at all ever works.
It’s hard to work real effectively when your head is ready to explode. But self-employment doesn’t come with paid sick days.
Things are hopping a bit around here these days, thanks to some short-term work helping out other devs. It’s always fun to come up to speed on a new project.
Here’s a commit message that showed up in the main Rails repository earlier today:
BACKWARDS INCOMPATIBLE: Renamed application.rb to
application_controller.rb and removed all the special casing that was in
place to support the former. You must do this rename in your own
application when you upgrade to this version [DHH]
Well, getting rid of special casing is great, and this commit does indeed simplify some of the Rails internals a bit. But I can hear some of my readers cursing: this seems like an arbitrary change just when Rails 2.2 is about to come out.
Fortunately, if you’re moving to Rails 2.2, this won’t affect you (yet). We’re close enough to 2.2 final that the main repository has been branched: there’s now a 2.2 stable branch (which is currently accepting very few bug fixes) and a master branch that’s targeted at Rails 2.3, or perhaps Rails 3.0. This change - and some other big changes that have been committed over the past few days - is on the master branch.
So, for Rails 2.2, don’t panic. On the other hand, if you’re tracking edge Rails closely, the next few weeks are likely to be a time of vast change (and instability) as some pent-up major changes hit the repository. Be sure you know what you’re cloning before you set up a new Rails application.
Lots of links piled up over the weekend. I’ll try to get something more substantive posted later.
With my latest project past its initial design spike and settling down into more routine stuff, I’m still looking for more to take on, especially into December and beyond.
Even though Rails 2.2 is officially in “release candidate” status, new features are still making their way into the source code tree. While we could debate the suitability of this from a release engineering point of view, some of the new features are certainly sweet. The latest is the addition of the :only and :except options to RESTful routes.
Normally, using map.resources creates routes for all seven of the default actions (index, show, new, create, edit, update, and destroy) for the resource. But in Rails 2.2 (or in the current edge builds), you can fine-tune this behavior. The :only option specifies that only certain routes should be generated:
map.resources :customers, :only => [:index, :show, :destroy]
As with most places in Rails, you can use :except as the opposite of :only:
map.resources :customers, :except => :index
That declaration would give you six of the seven default routes, omitting only a route for the index action.
In addition to an action or an array of actions, you can also supply the special symbols :all or :none to the :only and :except options.
Why do this? In addition to making your code easier to follow, the smaller you can make the routing table, the less memory it will take up - and the less processing time route recognition and generation will take. It can also lower the attack surface of your application by removing unused routes, which is a security win.
Well, I still have hours to sell, but a couple of little projects appear to be coming together, so hopefully I won’t be on the bench for too long.
You probably already know (well, if you’re a Rails developer) that you can use to_xml or to_json to quickly get XML or JSON representations of Active Record model instances. But did you know that these methods are configurable? By default they simply dump all of the attributes of the model along with their values, but if you want to do something different, you can - and usually without overriding the base methods.
To start, you can specify exactly which attributes to export with the :only or :except options:
@user.to_xml :only => [ :name, :phone ] @user.to_xml :except => :password @user.to_json :only => [ :name, :phone ] @user.to_json :except => :password
You can include associated records, nesting as needed, with the :include option:
@user.to_xml :include => {:orders =>
{ :include => [:shipments, :backorders] }}
@user.to_json {:orders =>
{ :include => [:shipments, :backorders] }}
:only and :except also work on includes:
@user.to_xml :include => {:orders =>
{ :include => [:shipments, :backorders] },
:only => :order_date }
@user.to_json {:orders =>
{ :include => [:shipments, :backorders] },
:only => :order_date }
You can create XML or JSON attributes from model methods by using the :methods option:
@user.to_xml :methods => :permalink @user.to_json :methods => :permalink
Additionally, there are some options that apply only to to_xml. :skip_instruct suppresses the XML processing instruction. :skip_types suppresses the output of types to the XML. :dasherize => false turns off dasherization of column names.
I’ve shut down and reformatted my Windows desktop for good (I hadn’t turned it on for six months or so, it just took me this long to get around to reformatting the drives). If anyone wants a deal on a Dell PowerEdge 1800 server before I EBay it, holler.
If you take a look at the Rails source code, you’ll find numerous useful comments like this one from ActionController::Base:
# All requests are considered local by default, so everyone # will be exposed to detailed debugging screens on errors. # When the application is ready to go public, this should be set to # false, and the protected method <tt>local_request?</tt> # should instead be implemented in the controller to determine # when debugging screens should be shown. @@consider_all_requests_local = true cattr_accessor :consider_all_requests_local
But if you check your favorite Rails API site for documentation of consider_all_requests_local, you’ll come up blank. What’s up?
I spent some time chasing this, and it turns out to be a conflict between the way that Rails is commented and the way that rdoc thinks things should be done. There’s actually a ticket in the old Rails Trac with a proposed resolution for this. As it happens, that ticket isn’t quite right, but it provoked rdoc into changing things. The secret lies in the rdoc 2.x support for documenting metaprogrammed methods.
To properly document cattr_accessor (and similar) declarations in your own Rails code, you need to do two things. First, upgrade from your musty old rdoc 1.0.1 to a more recent version - 2.2.1 is current. If you look at their downloads you will find there is a gem version, but just installing this may not be enough: putting the gem on my system gave me rdoc 2 from the command line but rdoc 1 from rake tasks. That’s because (at least on my Mac), rdoc is also out there in the ruby/1.8 standard tree, and so I had to replace the 1.0.1 there with the new bits.
Second, you need to change your markup comments to tell rdoc that this is a metaprogrammed method. Here’s the revision for that method from ActiveController::Base:
@@consider_all_requests_local = true ## # :singleton-method: # All requests are considered local by default, so everyone # will be exposed to detailed debugging screens on errors. # When the application is ready to go public, this should be set to # false, and the protected method <tt>local_request?</tt> # should instead be implemented in the controller to determine # when debugging screens should be shown. cattr_accessor :consider_all_requests_local
The ## indicator tells rdoc that this is a metaprogrammed method, which means it will ignore the first token on the declaration and pick up the second one as the method name. The # :singleton-method# indicator tells rdoc to document this as a class method rather than as an instance method.
The Rails Documentation team is exploring how we’ll fix up the core Rails source to use the new markers. Meanwhile, you should start using this anywhere that you have the cattr methods in your own code or plugins - and upgrade your rdoc bits in anticipation.
Yesterday saw my first posting to the official Rails weblog. A nice step on the way to world domination, I guess.
In Rails 2.2, if you include a belongs_to or references column in a call to the model generator, it will automatically add the belongs_to declaration to the model, as well as creating the foreign key column in the migration.
For example, run this from the command line:
script/generate model order order_date:datetime customer:belongs_to
And you’ll find that the generated Order model looks like this:
class Order < ActiveRecord::Base belongs_to :customer end
Nothing earthshaking, but it will save you a few keystrokes.
Personally, I think we ought to explore the possibilities of making the model generator much more full-featured. I don’t see any reason why it couldn’t build validations, associations, and accessibility declarations at generation time. As a first step on this road, I’ve submitted a Rails patch. If you like the idea (and you’ve got a copy of edge hanging around), go give it a try and let me know what you think.
I tossed out a few more bits of open source code over the weekend: a fork of suprails (though actually I hope the original project just merges my one tiny change), and a proposed change for Rails core (which you’re welcome to go test and, hopefully, +1).
Maybe it’s just me and the amount of support and writing I’m doing these days, but I find myself fairly frequently looking at a bit of core Rails code and wondering “what that in release X”? To help figure that out, here’s a list of Rails version release dates (starting with 1.0) pulled together from the svn and git repos:
12/13/05 1.0.0 3/22/06 1.1.0 RC1 3/28/06 1.1.0 4/06/06 1.1.1 4/09/06 1.1.2 6/28/06 1.1.3 6/30/06 1.1.4 8/09/06 1.1.5 8/10/06 1.1.6 11/23/06 1.2.0 RC1 1/05/07 1.2.0 RC2 1/18/07 1.2.0 1/18/07 1.2.1 2/06/07 1.2.2 3/14/07 1.2.3 10/05/07 1.2.4 10/12/07 1.2.5 11/24/07 1.2.6 9/30/07 2.0.0 PR (Preview Release) 11/09/07 2.0.0 RC1 11/29/07 2.0.0 RC2 12/07/07 2.0.0 12/07/07 2.0.1 (2.0 final) 12/16/07 2.0.2 5/11/08 2.0.3 9/04/08 2.0.4 10/19/08 2.0.5 5/11/08 2.1.0 RC1 5/31/08 2.1.0 9/04/08 2.1.1 10/23/08 2.1.2 10/24/08 2.2.0 (2.2 RC1) 11/14/08 2.2.1 (2.2 RC2)
It seems that a lot of the Rails applications I’ve been working on have a User model that has a many-to-many relation with a Role model, so that users can have a role like “admin” or “manager”, or even multiple roles. Along with this comes the necessity to conditionally show things in views. Recently I’ve started moving away from having explicit @current_user.has_role(”whatever”) calls in the views, to some code in the application_helper.rb file:
module ApplicationHelper
def admin_only(&block)
role_only("administrator", &block)
end
def manager_only(&block)
role_only("manager", &block)
end
private
def role_only(rolename, &block)
if not @current_user.blank? and @current_user.has_role?(rolename)
block.call
end
end
end
Now in views I can easily mark off sections that should be displayed to only one user type:
<% admin_only do %> <!-- administrator content goes here --> <% end %> <% manager_only do %> <!-- manager content goes here --> <% end %>
It would be easy to extend the role_only method to take an array of roles and check for membership in any of them, but I haven’t had need of that yet.
Hat tip to Aaron Longwell for introducing me to this technique.
Looks like I’ve got another bit of new business spinning up. This is good, though I’ve still got hours free.
Braid 0.5 - This tool for vendoring git and svn repos is moving along. (via RubyFlow)
The Rails Envy guys, Gregg Pollack and Jason Seifer, are back with another of their “Envycast” screencasts: 45 minutes about Ruby on Rails 2.2, which is scheduled to be released realsoonnow. They were kind enough to send me a review copy (which means, yes, I didn’t pay for it), and here are some impressions.
You certainly get enough for your money when you purchase their “Package Deal” for $16: the screencast itself in QuickTime, iPod/iPhone, and Ogg Theora formats, a 120-page PDF ebook by Carlos Brando in English and Portuguese, and a set of code samples (you can also buy the video or the ebook separately for $9 each).
Let’s take the pieces one at a time. Unlike some other screencasts, the Rails Envy guys are using green-screen technology to insert themselves in front of the slides and code samples. This adds some action to what might otherwise be a pretty dry pile of information though (fortunately, I think) the cheesy jokes are not as non-stop as in their classic “Ruby on Rails vs.
” commercials. They pack a pretty good amount of information into the screencast, touching on dozens of new features in the time they have; in some areas, they’re more comprehensive than the official release notes.
The PDF is even more comprehensive than the screencast; it covers a ton of stuff out of the changelogs, with code samples and explanations (in fact, it includes the changelogs as an appendix). If you want a complete overview of the changes coming down the pike for Rails 2.2, the PDF is the single best resource I’ve seen so far.
The code samples parallel the ebook; they’re set up as a series of tests, so you can run rake against it (this will be useful as 2.2 proceeds from RC1 to release, to see what might have changed), or dig in to test cases to see the new functionality in action.
So, is it worth the money? Well, you could get all of this information elsewhere: the Rails changelogs and source code and git repository are all public. In theory, it’s easy enough to look at the git logs going back from now to the 2.1 timeframe to see everything. But as someone who’s done just that (to help compile the 2.2 release notes), I can tell you it’s a non-trivial exercise. There’s a lot of stuff in the commit log that doesn’t make immediate sense, and there are older commits that have been changed by newer ones. This set of resources does all that work for you.
But, one caution: Rails 2.2 just reached the RC1 point, and while the code is mostly locked down, it’s still changing. The odds are pretty good that some part of this material will be obsolete when Rails 2.2 actually ships - and while it should be easy enough for Rails Envy to update the code and ebook, I’m not sure what they’ll do if there ends up being a bug in the screencast. Hopefully they have some plan for that.
If you’re considering whether to upgrade to 2.2, these resources will give you an early look at how you stand to benefit (as well as listing which 2.1 bugs have been fixed). Personally, I think the video is overkill, but I’m not all that much of a screencast fan; I can scan and even read written material much faster. But the ebook is definitely a valuable addition to the written material on Rails, and at $9, it should be a trivial amount of money for any developer to spend to get up to speed.
Looks like I’m looking for another consulting project; one major one just wrapped, so I have some pretty substantial hours open going into November.
There are a few guides floating around about how to contribute your own code to Rails. But none of them (or at least none of the ones that I found) walk you through every step of the way. So, here’s an attempt to fill that gap.
Step 0: Learn at least something about Ruby and Rails. If you don’t understand the syntax of the language, common Ruby idioms, and the code that already exists in Rails, you’re unlikely to be able to build a good patch (that is, one that will get accepted). You don’t have to know every in-and-out of the language and the framework; some of the Rails code is fiendishly complex. But Rails is probably not appropriate as the first place that you ever write Ruby code. You should at least understand (though not necessarily memorize) The Rails Way
and The Ruby Programming Language.
Step 1: Install git. You won’t be able to do anything without the Rails source code, and this is a prerequisite. The git homepage has installation instructions. If you’re on OS X, use the Git for OS X installer. Everyday Git will teach you just enough about git to get by. The PeepCode screencast on git ($9) is easier to follow.
Step 2: Get the Rails source code. Don’t fork the main Rails repository. Instead, you want to clone it to your own computer. Navigate to the folder where you want the source code (it will create its own /rails subdirectory) and run:
git clone git://github.com/rails/rails.git
Step 3: Set up and run the tests. All of the Rails tests must pass with any code you submit, otherwise you have no chance of getting code accepted. This means you need to be able to run the tests. For the tests that touch the database, this means creating the databases. With MySQL:
mysql> create database activerecord_unittest;
mysql> create database activerecord_unittest2;
mysql> GRANT ALL PRIVILEGES ON activerecord_unittest.*
to 'rails'@'localhost';
mysql> GRANT ALL PRIVILEGES ON activerecord_unittest2.*
to 'rails'@'localhost';
If you’re using another database, check the files under activerecord/test/connections in the Rails source code for default connection information. You can edit these files if you must on your machine to provide different credentials, but obviously you should not push any changes back to Rails.
Now if you go back to the root of the Rails source on your machine and run rake with no parameters, you should see every test in all of the Rails components pass. After that, check out the file activerecord/RUNNING_UNIT_TESTS for information on running more targeted tests.
Step 4: Fork Rails. You’re not going to put your patches right into the master branch, OK? Think of a name for your new branch and run
git checkout -b my_new_branch
It doesn’t really matter what name you use, because this branch will only exist on your local computer.
Step 5: Write your code. You’re on your branch now, so you can write whatever you want (you can check to make sure you’re on the right branch with git branch -a). But if you’re planning to submit your change back for inclusion in Rails, keep a few things in mind:
Step 6: Sanity check. You know at least one other Rails developer, right? Show them what you’re doing and ask for feedback. Doing this in private before you push a patch out publicly is the “smoke test” for a patch: if you can’t convince one other developer of the beauty of your code, you’re unlikely to convince the core team either.
Step 7: Update your copy of Rails. It’s pretty likely that other changes to core Rails have happened while you were working. Go get them:
git checkout master git pull
Now reapply your patch on top of the latest changes:
git checkout my_new_branch git rebase master
No conflicts? Tests still pass? Change still seems reasonable to you? Then move on.
Step 8: Create your patch. Still in your branch, run
git commit -a git format-patch master --stdout > my_new_patch.diff
Sanity check the results of this operation: open the diff file in your text editor of choice and make sure that no unintended changes crept in.
Step 9: Create a Lighthouse account. You will need one to send in a ticket with your patch. You can do this at the free signup page.
Step 10: Create a ticket with your patch. Go to the Rails Lighthouse page. Sign in if necessary. Click on “Add New Ticket.” Fill in a reasonable title and description, remember to attach your patch file, and tag the ticket with the ‘patch’ tag and whatever other subject area tags make sense.
Step 11: Get some feedback. The Contributing to Rails page suggests using the rubyonrails-core mailing list or the #rails-contrib channel on IRC freenode for this. You might also try just talking to Rails developers that you know.
Step 12: Lather, rinse, release. It’s entirely possible that the feedback you get will suggest changes. Don’t get discouraged: the whole point of contributing to an active open source project is to tap into community knowledge. If people are encouraging you to tweak your code, then it’s worth making the tweaks and resubmitting. If the feedback is that your code doesn’t belong in the core, you might still think about releasing it as a plugin.
And then…think about your next contribution!
