New Rails plugin: AttrLocked

I just released a new plugin for Rails, called AttrLocked. It lets you specify that certain model attributes should not be changeable once a record has been created – perfect for making sure usernames are fixed or your financial data doesn’t get tampered with. It will not let you change a record’s locked attributes in any way, and will disable form fields as appropriate to stop people bothering to change the data. Example:

class Payment < ActiveRecord::Base
  attr_locked :time, :amount, :transaction_id
end

Now, when you grab a record from the database, using time=, amount= and transaction_id= won’t work. attributes=, save and update_attributes will silently ignore the locked attributes, and update_attribute will return false if you try to modify a locked attribute. Naturally, you are allowed to set values on new records.

I’ve only tested it on my current project, which is in Rails 1.2.2, but I’d really appreciate testing with other applications. Install like so:

script/plugin install
    git://github.com/jcoglan/attr_locked

If you’ve enjoyed this article, you might enjoy my recently published book JavaScript Testing Recipes. It’s full of simple techniques for writing modular, maintainable JavaScript apps in the browser and on the server.