Jesse Newland

264 Posts tagged with rails

Speed up your Rails XML responses | Rails on the Run

How to turn off auto_increment in Rails Active Record - Stack Overflow

Where's the bloat: Tracking 'require' memory usage in Ruby and Rails

Among the other awesome things that Ruby Enterprise Edition’s inclusion of the RailsBench GC patch provides is the addition of the allocated_size method on Ruby’s GC constant.

Eric Lindvall recently devised a very clever use for this GC.allocated_size method:

If I wanted to see what was contributing to the large memory footprint of an application on startup, tracking how much memory was allocated during each require would give me a good place to start.

Given the size of GC.allocated_size before and after require calls, we can determine the initial memory profile of any ruby gem, library, file, or Rails model.

To use this to determine the initial memory profile of a beefy Rails application, you’ll first want to download his require_tracking hax. Then, load your production Rails application’s environment with require_tracking turned on:


RAILS_ENV=production ruby -r/tmp/require_tracking.rb  -e "require 'config/environment'"
Memory used by file:
                                     File KB
                            ------------- --------
                      config/environment: 209,623
/srv/myapp/releases/20091230003757/app/models/user: 73,653
/srv/myapp/releases/20091230003757/app/models/store: 70,962
                           ./config/boot: 15,021
/srv/myapp/releases/20091230003757/app/models/discount_code: 9,813
/srv/myapp/releases/20091230003757/app/models/order: 9,390
./config/../vendor/rails/railties/lib/initializer: 9,348
...

71.9 M used by the User model? Holy wow! I know what I’ll be doing today….

Creating your own generators with Thor | Plataforma Tecnologia Blog

Spinning up a new Rails app « Katz Got Your Tongue?

Looks like Yehuda finally un-broke creating a new Rails app. And there was much rejoicing!

Production Rails Tuning with Passenger: PassengerMaxProcesses

Setting Up Cucumber to Use Webrat and Selenium with Rails « Kevin Colyar

Running Rails performance tests on real data

Force performance tests to use a 'performance' database (containing a production-like data set you provide), which will not get wiped on every run.

Railscasts - Delayed Job

In which Ryan Bates covers delayed_job. If you write Rails apps and have never used DJ before, check this out now. It'll change your life.

rails's rails at v2.3.3 - GitHub

Rails 2.3.3 is around the corner...

Finding Memory Leaks with Bleak House

Compiling & Running Bleak House on Leopard

Ruby at ThoughtWorks

ThoughtWorks started using Ruby for production projects in 2006, from then till the end of 2008 we had done 41 ruby projects. In preparation for a talk at QCon I surveyed these projects to examine what lessons we can draw from the experience.

Default Scopes and Inheritance to the rescue

Pratik on how to use Inheritance without STI

railsmachine's moonshine at master - GitHub

Rails deployment and configuration management done right. ShadowPuppet Capistrano == crazy delicious

Google Data on Rails - Google Data APIs - Google Code

Using Gravatar as a fallback avatar with Paperclip

Rails Migration to convert latin1 MySQL DB to UTF8

Ruby on Rails dictionary for Mac OS X

Engines in Rails 2.3

Engines made a comeback in 2.3, here's an overview of what they can do.

Ruby on Rails 2.3 Release Notes

Ryan's Scraps: What's New in Edge Rails: Nested Object Forms

"...the most requested feature for Rails 2.3 - the ability to handle multiple models in a single form - is here"

The technical story of Muxtape

"How long do you think it would take to re-write the site in Rails?" "Umm, well..", Cmd-T, "localhost:3000", Enter, "It already is." Now *that's* how you sneak ruby into the system.

First draft of Rails 2.3 release notes

From http://github.com/lifo/docrails. ~400 lines of changes.

Riding Rails: Nested Model Forms

finally

Screencast : How to Create a File Upload Progress Bar in Rails, Passenger, Prototype and Low Pro - Rails Ill.

Rails Metal: a micro-framework with the power of Rails: \m/

Updates:

  • Clarified the distinction between Rails Metal and Rack middleware after more information from @Josh in the comments. Thanks!
  • Read more about metal from DHH on the Official Rails Blog.
  • Demonstrate Testing Metal end points
  • Update Poller example to match new style
  • Cover Sinatra Integration
  • Correct benchmarks

Josh Peek committed a new feature to Edge Rails today: Rails Metal. After the recent work to replace Rails’ crufty request processing code with Rack and integrate its middleware support, Rails Metal is a logical progression that allows Rails apps to use the power of Rack middleware to create super-fast actions.

For example, here’s a sample “Hello World” Metal:

  class Poller < Rails::Rack::Metal
    def call(env)
      if env["PATH_INFO"] =~ /^\/poller/
        [200, {"Content-Type" => "text/html"}, "Hello, World!"]
      else
        [404, {"Content-Type" => "text/html"}, "Not Found"]
      end
    end
  end

And for comparison, a “Hello World” controller:

    class OldPollerController < ApplicationController
      def poller
        render :text => "Hello World!"
      end
    end

So, let’s fire up ruby script/server and see what this gives us:

  # traditional Controller
  $ curl 127.0.0.1:3000/old_poller/poller
    Hello World!

  # the new Metal
  $ curl 127.0.0.1:3000/poller
    Hello World!

So, the point of all of these other “micro-frameworks” is that they’re faster than Rails, right? Let’s benchmark this new “Hello World” Metal:

  # first, let's benchmark the traditional controller
  $ ab -n 1000 http://127.0.0.1:3000/old_poller/poller
  ... snip ...
  Requests per second:    408.45 [#/sec] (mean)
  Time per request:       2.448 [ms] (mean)

  # now for the Metal middleware
  $ ab -n 1000 http://127.0.0.1:3000/poller
  ... snip ...
  Requests per second:    1154.66 [#/sec] (mean)
  Time per request:       0.866 [ms] (mean)

For this trivial “Hello World” benchmark, Rails Metal is 2.8x faster than a Controller. Awesome. Have a couple actions of your app you need to optimize? Instead of breaking them out into a separate application using a micro-framework, add a Metal inside your existing app. You get the performance benefits of processing requests outside of ActionPack, and it’s all integrated as a part of your Rails app. Easy!

Sinatra Metal

You can now also use Sinatra to create Metal end points:

  Sinatra::Application.default_options.merge!(:run => false, :env => 
  :production)
  Api = Sinatra.application unless defined? Api

  get '/interesting/new/ideas' do
    'Hello Sinatra!'
  end

First person to show the use of a Merb app as a Metal end point wins a prize.

Standalone Execution

Additionaly, Rails Metal are able to be executed in a separate process from your Rails application using rackup:

  rackup -s mongrel app/metal/poller.rb

This runs the Poller Metal separeately from Rails, on it’s own port (rackup defaults to 9292). This is perfect if you have an action that’s taking a very long time (for example a file upload) that you’d like to split out from the normal Rails request processing queue.

Testing Metal

Update: After several people commented asking how to test metal, DHH chimed in and recommend Integration Testing for Metal end points, as they hit the whole stack, and I submitted a patch cleaning up the Integration Testing behavior of Metal. Testing Metal end points now works just like any other Integration test:

      class PollerTest < ActionController::IntegrationTest
        test "poller returns hello world" do
          get "/poller"
          assert_response 200
          assert_response :success
          assert_response :ok
          assert_equal "Hello World!", response.body
        end
      end

Fun With Middleware

So, essentially, Rails Metal is a thin wrapper around Rails’ new Rack middleware support. Rack middleware is pretty powerful stuff: framework-independent components that process requests independently or in concert with other middleware. For example, here’s a simple piece of Rack middleware that runs a regex on responses:

class RegexMiddleware
  def initialize(app)
    @app = app
  end

  def call(env)
    status, headers, response = @app.call(env)
    new_response = []
    response.each do |part|
      new_response << part.gsub(/World/, 'Middleware')
    end
    [status, headers, new_response]
  end
end

To use this rack middleware in Rails, add this line to your environment.rb

Rails::Initializer.run do |config|
  ...
  config.middleware.use RegexMiddleware
end 

Restart your server, and check out what happens:

  $ curl 127.0.0.1:3000/poller
    Hello Middleware!

The Rack middleware filtered the output of the Metal we created before. This works with output generated by normal controllers and everything too. The possible uses of this pattern are endless:

  • Single Sign On
  • Request/Response Signing (think OAuth)
  • Asset Compression

rack-contrib is a nice collection of Rack middleware if you’re interested in more examples.

Rails Metal is a simple wrapper around the existing (yet undocumented) Rack middleware support in Edge Rails that attempts to DRY the process of using middleware to create endpoints (like a poller) as opposed to filters (which are better implemented as traditional middleware, like the examples above). For example, Rails Metal might be used:

  • To speed up a ‘poller’ action called by all active users of a popular web-based chat application every 3 seconds (hint: Campfire).
  • To improve the performance of any API endpoint
  • To process file uploads outside of the Rails request queue
  • To authorize delivery of cached content

We don’t need no stinking micro-frameworks

With the additional of Metal and Rack middleware support, Rails effectively includes a micro-framework of its own; one that either tighly integrates with Rails or is executed separately – whichever the need dictates.

This is a great response by the Rails team to all of the buzz surrouding micro-frameworks: a micro-framework with the power of Rails. I’m definitely going to try this approach to squeeze a couple extra requests per second out of a heavily trafficked API call – let me know in the comments if you find a use for it.

Read up a bit more on Rack and then take a look at Josh’s commit Introducing Rails Metal (and the ensuing comments) if you’re interested for more information.

Phusion Passenger 2.0.6 released

Fixes Ruby 1.8.5 compatibility

Launching Ruby on Rails projects, a checklist

A nice sanity checklist for the big launch.

cache-money

A Write-Through Caching Library for ActiveRecord, in production use at Twitter.

Rails templates

Oh, this is hot hot sauce.

Ruby on Rails guides

Ryan's Scraps: What's New in Edge Rails: Rails 2.2 Released - Summary of Features

Thread safety for your Rails

What thread safety means in the context of Rails 2.2

bong

Hit your website with bong. Uses httperf to run a suite of benchmarking tests against specified urls on your site.

jnunemaker's user_stamp

A Rails plugin that adds the ability to automatically stamp each record with the currently logged in user.

Panda - Open source video platform

Panda is a Merb app which runs on a special EC2 instance to encode videos for you. Uploaded videos are stored on S3 with a small amount of info kept in SimpleDB. The REST API makes it easy to integrate user video uploading into your web application.

Another comparison of HAProxy and Nginx « Affection Code

HAProxy maxconn 1 outperforms Nginx fair by a longshot. Let the load balancing part of your stack handle request queuing, not mongrel. That's not "fair" by any means.

The Rubyist

The Rubyist is a technical magazine focused on Ruby, Rails, Merb, and anything else that surrounds the programming language that we all know and love. Ordering my copy now.

A Thinking Man's Sphinx

ReinH explores the differences between UltraSphinx and ThinkingSphinx, and explains why is awesomer.

Thinking Sphinx

A concise and easy-to-use Ruby library that connects ActiveRecord to the Sphinx search daemon, managing configuration and searching.

Redesign your site in place using Rails custom mime types

Nifty use of Rails' mime-type support to support a 'beta' request format

The Rails Documentation App - Rails-doc.org

Lightning-fast keyword search with weighed sorting and community based notes inline with the documentation

Rails Framework Documentation

Edge rails docs generated nightly from the docrails project

The Endless Page

A nice implementation of the Endless Page AJAX Pattern

A List Apart: Issue 257 - The why and how of Ruby on Rails

ALA Takes on Ruby on Rails with two articles - one from my good friend Dan Benjamin, and another from Michael Slater

masquerade

masquerade is an Rails OpenID server released under the MIT-license

Rails 2.1 Time Zone Support: An Overview

Nice walkthrough of the new Rails TimeZone support

bounce

Nice, clean pattern for 301 redirects

Riding Rails: Rails is moving from SVN to Git

Edge Rails gets Declarative Gem Dependencies

config.gem 'GEMNAME' in environment.rb declares a gem as required. `rake gems:install` will then install all required gems.

ActiveRecord::Dirty

ActiveRecord now tracks changes to unsaved attributes

RailRoad diagrams generator

RailRoad is a class diagrams generator for Ruby on Rails applications.

bundle-fu

CSS/JS asset bundling plugin

ride_the_fireeagle

a Rails plugin that easily integrates your app with Fire Eagle, by yours truly

What's New in Edge Rails: Has Finder Functionality

Nick Kallen’s wildly popular has_finder plugin was just added to Edge, now called 'named_scope'

NestedHasManyThrough

This plugin makes it possible to define has_many :through relationships that go through other has_many :through relationships, possibly through an arbitrarily deep hierarchy

Paperclip

Paperclip is intended as an easy file attachment library for ActiveRecord. The intent behind it was to keep setup as easy as possible and to treat files as much like other attributes as possible.

rails_environments

Pretty Rails.production?, Rails.development?, Rails.test? and Rails.environment methods

assert_valid_markup

Validate your (X)HTML against the W3C Validator web service from within your functional tests.

Fire Eagle - Easily share your location online! Personalise lots of sites and services!

The first Rails app launched by Yahoo!. This is one sick web service

NginxHttpUpstreamFairModule

The upstream_fair module sends an incoming request to the least-busy backend server, rather than distributing requests round-robin.

Is edge Rails broken?

The latest in a meme I'm calling Boolean Web Services. Someone needs to write a standard for these and craft up a gem to consume them, i.e. BooleanWebService.new(:israilsbroken) => false

RailRoad diagrams generator

RailRoad is a class diagrams generator for Ruby on Rails applications.

The NullDB Connection Adapter Plugin

NullDB is the Null Object pattern as applied to ActiveRecord database adapters. It is a database backend that translates database interactions into no-ops.

Tarantula vs. your Rails app

Fuzzy Spider Integration Test, inspired by SpiderTest

db-populate

Plugin to help populate the development and production databases of Ruby on Rails projects

Simple Ruby SMTP Server / ActiveRecord Importer

SMTP server that imports emails sent to it into ActiveRecord

Process title support for Mongrel

This is a simple module which changes Mongrel's process title to reflect what it's currently doing. You can then determine a given Mongrel server's status using ps

Fixing attachment_fu on Edge Rails

Edge changeset 8664 introduces ActiveSupport::Callbacks. This currently breaks attachment_fu's callback internals and may affect other plugins as well...

delayed_job

Database based asynchronously priority queue system -- Extracted from Shopify

searchable

Adds a simple #search class method that does SQL searching behind the scenes.

pseudo_primary_key

Overrides find_one and to_param to use the given attribute

attr_hidden

Excludes attributes from serialization methods like to_xml and to_json

Nginxr

A ruby wrapper for nginx config files

When, a Rails plugin

Adds :if and :unless modifiers to before_filters, most ActiveRecord callbacks, and validations.

canhaschat

An XMPP chat plugin for use w/ Rails

What do you want to see in mod_rubinius?

Ezra asks the community...

backup_fu Makes Amazon S3 Backups Redonkulously easy

starling and asynchrous tasks in ruby on rails

a plugin called 'workling' that integrates starling into your rails app

git-rails

git-rails is a simple tool to help manage your rails app with git

FastSessions

Clever optimizations to Rails Sessions

Timezone awareness in Rails -- techno weenie

Hot new TimeWithZone support in Rails

Guerrilla's Guide to Optimizing Rails Applications

The Battle For Performance

SwitchPipe - Process Manager and Proxy for Rapid Web App Deployment

Version 1 of Peter Cooper's take on the 'Rails Deployment is Hard' problem.

Rails truncate helper that handles HTML tags and entities

truncate_html()

Savage Beast 2.0

Beast (a Rails forum), as a plugin, for Rails 2.0

Dr Nic » Get ready for the TextMate “Trundle to Rails 2.0 Bundle”

Dr. Nic has taken over and updated the Ruby on Rails TextMate bundle.

YAWS (Erlang) frontend for rails apps

Fuzed is a project attempting to use YAWS and erlang distribution to replace the conventional many-parts mongrel revproxy solution. Ultimately, the goal of the Fuzed project is to make a system which can easily deploy a rails app onto EC2

RailsConf 2008 Registration

Sign up quick - RailsConf sold out in 3 weeks last year

RSpec plain text story runner

Hot

SoftValidations

Provides an additional AR::Errors object, referred to as warnings, to ActiveRecord objects. Useful for noting that objects are valid but not in the desired 'complete' state.

friendly_id

Rails plugin for generating URL slugs. Automatically generates redirects if the field used to generate the slug changes

Rails Machine will be throwing a party at acts_as_conference

Get your pimp cups ready

Spreedly

A web service for handing subscription payments for other web services. Written in Rails. ActiveResource REST API. I think my head just exploded.

evented starling

defunkt is a badass. that is all.

AttributeFu

Syntactic sugar for multi-model forms

Rendering form partials

Syntactic sugar for the form-in-a-partial pattern

efficient-sql

To ensure your test cases call efficient MySQL

query-reviewer

An advanced mysql query analyzer for rails: runs 'EXPLAIN' before each of your select queries in development and summarizes query warnings.

sudo gem install starling

Starling is a light-weight persistent queue server that speaks the MemCache protocol. It was built to drive Twitter's backend, and is in production across Twitter's cluster.

Desert

Desert is a component framework for Rails that allows you to seamlessly define Models, Controllers, Views, Helpers, Routes, Migrations, and Plugin Dependencies in your plugins.

acts_as_state_machine

Great intro to acts_as_state_machine

Enhanced Acts As State Machine

A small enhancement to the very useful Acts As State Machine

simply_versioned

SimplyVersioned is a simple, non-invasive, approach to versioning ActiveRecord models

skynet

Skynet is an open source Ruby implementation of Google’s Map/Reduce framework, created at Geni.com. With Skynet, one can easily convert a time-consuming serial task, such as a computationally expensive Rails migration, into a distributed program running

rspec-on-rails-matchers

A collection of RSpec Matchers focused on specing Ruby on Rails projects

ZSFA -- Rails Is A Ghetto

In which Zed rants

Minimal Cart..

MinimalCart is very lightweight shopping cart plugin for Rails that leverages ActiveMerchant as a payment gateway.

Paginatin' Christmas — err.the_blog

will_paginate resources

acts_as_monkey

A Sample Rails' plugin for those not wise in the ways of science. Or something.

Jibberish

Javascript Localization for use with Gibberish

Beanstalk Messaging Queue

topfunky takes on Beanstalk

BackgrounDRb 1.0 released

Nice overview of the re-worked BackgroundDRb

Signal Wiki

Simple Rails Wiki

Beanstalk Client

This is a Ruby client library for the Beanstalk protocol.

Async Observer

Async Observer is a Rails plugin that provides deep integration with Beanstalk

The Rails Way (Book Review)

Lengthy review of my next deadtree purchase - The Rails Way by Obie Fernandez

spawn

This plugin provides a 'spawn' method to easily fork OR thread long-running sections of code so that your application can return results to your users more quickly.

Rails Edge Change: How to add a counter cache to an existing db table

A little gotcha that hit me recently as well

What's New in Edge Rails: Pluggable Controller Caching

Looks like the Rails caching code is getting some refactoring, as well as some new cache key management code.

Microformat helper for Ruby on Rails

The plugin currently provides helper methods for hAtom, basic hCard, and the datetime design pattern.

if_modified, second

Nice, clean approach to HTTP caching in Rails

DeHorrible: RESTifying SimpleDB

DeHorrible is a Rails proxy that RESTifies SimpleDB. Or if you insist, GETStifies your resources to use SimpleDB. Either way, it will keep your sensibilities intact.

Backgroundjob

Backgroundjob (Bj) is a simple to use background priority queue for rails.

RSpec 1.1

Tons of goodies, including the RSpec Story Runner.

SuperInPlaceControls

Better In-place Controls for Rails 2.0

Interlock

Interlock makes your view fragments and associated controller blocks march along together. If a fragment is fresh, the controller behavior won‘t run. It also automatically tracks invalidation dependencies based on the model lifecycle.

better rails caching

evan takes on caching

Beanstalkd

beanstalkd is a fast, distributed, in-memory workqueue service. Its interface is generic, but is intended for use in reducing the latency of page views in high-volume web applications by running most time-consuming tasks asynchronously.

Riding Rails: Rails 2.0: It's done!

DHH's writeup of Rails 2.0

Rails 2.0.1

In the true Rails tradition, 2.0.1 is out before anyone knew about 2.0.0 :)

Display Validation Errors For Your Ajaxified Form

Nice pattern for displaying validation errors for an AJAX-ed Form

Streamlined - Trac

Streamlined is a plugin for Ruby on Rails that provides an instant, production-ready UI for your ActiveRecord models.

Panasonic Youth – MultiRails 0.0.3 released

MultiRails lets you test your Rails plugin or app against many versions of Rails in one sweep.

Rails 2.0 Final Released!

Summary of Rails 2.0 Features

Rails 2.0 is out!

Setting up a new Rails app with Git

Want to be a dark-knight git-wielding Rails coder? Here’s a quick run-through of how you might set up git with a new Rails app.

[ANN] Giston; Piston lookalike for Git

Giston is a simple tool to help track svn vendor branches in your git repository. It’s loosely based on the idea of piston, but it’s more simplistic and it does less.

11 Tips on Hiring a Rails Developer

How to hire a good Rails Developer

RubyWorks Production Stack on Amazon EC2

RubyWorks EC2 Capistrano Recipes

err.the_blog.find_by_title('Evil Twin Plugin')

Duck-punch your Rails plugins without pissing off the Duck. Or something.

CarryOn

A plugin that allows you to freeze gems into vendor, including compiled extension for multiple platforms (!!!)

Masochism

Connection proxy sends some queries (thoes in a transaction, update statements, and ActiveRecord::Base#reload) to a master database, and the rest to the slave database

MultiRails

MultiRails allows easy testing against multiple versions of Rails for your Rails specific gem or plugin.

iPhone subdomains with Rails

sliding_session_timeout

By default, sessions in Rails expire at a fixed time from the moment they are created. This plugin lets you configure your sessions to expire in a sliding window, a fixed time from the last page view.

Cache-Control Header for Amazon S3

Nice quick monkey patch to save some cash on your s3 bill when used with attachment_fu

lazy_record

Proof of concept Lazy-Loading for ActiveRecord. Inspired by the 'kickers' of Ambition.

Ajax Pagination in less than 5 minutes

just implemented this. slick

Mongrel Cluster and Monit - pmade inc.

A ruby script to update a monitrc file with the necessary configuration to monitor your entire mongrel cluster

response_for

Allows you to decorate the respond_to block of actions on sublcassed controllers

Almost Painless Nested Resources

Nice DRY pattern for creating controllers that can be accessed in a nested scope and at root.

to_model, a complement for dom_id

Nice little hack: dom_id(@foo).to_model == @foo

MultiAppRouting

The goal of the MultiAppRouting plugin is to allow easy linking between multiple rails applications on different hosts.

deciphering objects.log

Nice email by Zed Shaw on how to interpret the output from some of the Mongrel debugging tools to find memory leaks in your app.

identity-matcher - Google Code

This code, extracted from the Rails codebase of dopplr.com, extends your User model with methods to pull in social network information from sites such as GMail, Twitter, Flickr, Facebook and any site supporting appropriate Microformats.

redirect_routing

map.redirect 'test', 'http://jnewland.com' OR map.redirect 'test', :controller => :test, :action => :index

nginx ssl rails

Ruby on Rais 2.0.0 Preview Release

Hot off the presses.

Rails on the Run - Ajax Pagination in less than 5 minutes

will_paginate meets lowpro. awesomeness.

QuarkRuby: Ruby on Rails Security Guide

Good guide for a due diligence security review on any public rails app.

resource_this - DRY Rails Resource Controllers

I’ve always been annoyed at the lack of maintainability that comes with using multiple resource controllers in my Rails apps. Each generated resource controller clocks in at 85 lines, and most of mine only differ from each other by a line or two – an added before_filter or a change in the url that the users is redirected to after the creation of a new Widget. Not very DRY. When coming back to each one of these controllers to add or adjust features, it takes me entirely too much time to sift through the stock 85 lines and find my application-specific behavior.

Enter resource_this

git clone git://github.com/jnewland/resource_this.git

resource_this aims to solve this maintainability problem by making your stock resource controllers look like this:

  class PostsController < ActionController::Base
   resource_this
  end

Behind the scenes, this code is generated:

  class PostsController < ActionController::Base
    before_filter :load_post, :only => [ :show, :edit, :update, :destroy ]
    before_filter :load_posts, :only => [ :index ]
    before_filter :new_post, :only => [ :new ]
    before_filter :create_post, :only => [ :create ]
    before_filter :update_post, :only => [ :update ]
    before_filter :destroy_post, :only => [ :destroy ]

  protected
    def load_post
      @post = Post.find(params[:id])
    end

    def new_post
      @post = Post.new
    end

    def create_post
      @post = Post.new(params[:post])
      @created = @post.save
    end

    def update_post
      @updated = @post.update_attributes(params[:post])
    end

    def destroy_post
      @post = @post.destroy
    end

    def load_posts
      @posts = Post.find(:all)
    end

  public
    def index
      respond_to do |format|
        format.html
        format.xml  { render :xml => @posts }
        format.js
      end
    end

    def show          
      respond_to do |format|
        format.html
        format.xml  { render :xml => @post }
        format.js
      end
    end

    def new          
      respond_to do |format|
        format.html { render :action => :edit }
        format.xml  { render :xml => @post }
        format.js
      end
    end

    def create
      respond_to do |format|
        if @created
          flash[:notice] = 'Post was successfully created.'
          format.html { redirect_to @post }
          format.xml  { render :xml => @post, :status => :created, :location => @post }
          format.js
        else
          format.html { render :action => :new }
          format.xml  { render :xml => @post.errors, :status => :unprocessable_entity }
          format.js
        end
      end
    end 

    def edit
      respond_to do |format|
        format.html
        format.js
      end
    end

    def update
      respond_to do |format|
        if @updated
          flash[:notice] = 'Post was successfully updated.'
          format.html { redirect_to @post }
          format.xml  { head :ok }
          format.js
        else
          format.html { render :action => :edit }
          format.xml  { render :xml => @post.errors, :status => :unprocessable_entity }
          format.js
        end
      end
    end

    def destroy          
      respond_to do |format|
        format.html { redirect_to :action => posts_url }
        format.xml  { head :ok }
        format.js
      end
    end
  end

Nested resources like so:

  class CommentsController < ActionController::Base
    resource_this :nested => [:posts]
  end

This generates a very similar controller to the one above with adjusted redirects and one additional before_filter / loader method pair to grab the parent resource. In this case:

  before_filter :load_post

  def load_post
    @post = Post.find(params[:post_id])
  end

The separation of logic – DB operations in before_filters, rendering in the standard resource controller methods – makes this approach ridiculously easy to customize. Need to load an additional object for the :show action? Slap another before_filter on it. Need to change the path that the :update action redirects to? Override the :update action with your new rendering behavior. And this customized behavior sticks out like a sore thumb – making it infinitely easier to maintain.

Oh, there’s also a generator:

./script/generate resource_this FooKlass [title:string body:text]

This works just like the resource generator, with the addition of the resource_this line to your controller and a functional test. No views are generated, so the test focuses on the XML behavior of this controller.

Contributing

resource_this is hosted on GitHub, so feel free to fork it and send a pull request with your changes.

resource_this

Not scaffolding. Resourcing. Creates extremely customizable resource controllers with one line of code.

themer

a template lookup system on top of standard Rails rendering pipeline.

monkeycharger

Small, standalone Rails app that does nothing but store and process credit card payments. Designed to be used via ActiveResource.

Sending SMS messages from your Rails application

For those times when you can't just use Twitter.

Ambition - SQL generation using Ruby's Enumerable class

Wanstrath is crazy smart. This is crazy awesome: User.detect { |u| u.email =~ 'chris%' && u.profile.blog == 'Err' }

Rails Chatter » Blog Archive » Ruby on Rails: Using Nested Resources with Polymorphic Associations

Nice writeup on how to DRY up nested resources w/ polymorphic associates on an amazingly ugly blog. Methinks this should be a plugin.

acts_at_rateable

simple Rails plugin for providing poloymorphic ratings

Synaphy · Seesaw - High-Availability Mongrel Packs

Seesaw allows you to perform a rolling restart of your mongrel cluster without dropping a single request.

PermalinkFu

A simple plugin extracted from Mephisto for creating permalinks from attributes.

err.the_blog.find_by_title('Be Dee Dee and Me')

Can't believe I haven't bookmarked this before. A GREAT guide to behavior driven development.

Secure UTF-8 Input in Rails - igvita.com

Great overview of what's necessary to ensure your Rails app speaks UTF-8

autotest growl Doomguy

Awesome. Makes TDD fun :)

growing up your acts_as_taggable :: snax

Replacing acts_as_taggable w/ the wonderful has_many_polymorphs

Portable Social Networks at Mashup Camp :: UltraNormal

Demo Rails app that imports hCard information and XFN friends after an OpenID authentication. Rawk.

A taxonomy of Rails plugins

Was just looking for this today. Perfect.

Noobkit Docs, Ruby on Rails API documentation... on Rails.

Very nice Rails, Ruby core, and Rubygems documentation, w/ comments!

has_many_polymorphs for dummies

has_many :through for polymorphic relationships

MakeResourceful

Oy. Nice, simple, auto-creation of REST controllers. Encourages fat models. Rawk.

From Rails Ajax helpers to Low Pro, Part 2

Writing unobtrusive Javascript using Low Pro

CachableFlash

This plugin enables greater levels of page caching by rendering flash messages from a cookie using JavaScript, instead of in your Rails view template.

MileMarker

A Ruby on Rails plugin for visually setting expectations throughout application development. MileMarker adds a helper for marking page elements with the milestone they are slated to be developed, and makes them unable to be interacted with.

Scale rails from one box to three, four and five

c3 on scaling rails apps. good advice.

How to Profile Your Rails Application

Dig into your slow code with ruby-prof

Pivotal Blabs : Access Control &amp; Permissions in Rails

Nice writeup of a very concise and readable access control pattern

Warehouse — Subversion Browser

Never before has there been a web-based Subversion browser that is as beautiful as it is simple.

Jake@Nitobi » Blog Archive » RobotReplay and Rails on Amazon EC2

"Don’t forget actually deploying changes to your app. Capistrano is great, awesome, wicked, but needing to rewrite your deploy.rb as you add and remove servers on EC2 is teh sux." I know, I'm working on it :).

code_fu - AJAX file uploads in Rails using attachment_fu and responds_to_parent

AJAX-y file uploads with attachment_fu using an IFRAME trick. Slick

Mike Clark's Weblog - File Upload Fu

An incredible detailed tutorial for using attachment_fu

Testing with attachment_fu · Fingertips

Nice tip to make testing attachment_fu a bit friendlier.

RubyWorks production stack - from ThoughtWorks

RubyWorks production stack is a collection of open-source software required to host a RubyOnRails application on a RedHat Enterprise Linux 4 or CentOS 4 server

RailsConf '07 Roundup

David Heinemeier Hansson, by James Duncan Davidson. Creative Commons BY-NC-ND

I spent the past several days in Portland, OR, for RailsConf, the yearly gathering of the vibrant Ruby on Rails community. O’Reilly Media and Ruby Central put on an incredible conference. My only disappointment was that I couldn’t attend all of the presentations. Luckily, most of the presentation slides are online (some with accompanying code!!):

But by far, the most valuable part of the whole event was the time I spent in the hallways and around Portland with other Rails developers. In the two years I’ve been working with Rails, I’ve networked and collaborated with dozens if not hundreds of Rails developers online. It was great to finally be able to associate faces and voices with their respective names, blogs, and chat handles.

I also wrangled Erik Kastner and Charles Brian Quinn into the Capazon project while in Portland – look for some updates on that front in the near future.

A special thanks to the following folks for making my RailsConf an especially great time:

More RailsConf slides

From the wiki

RailsConf07 Presentation Archive

All of the goodness from RailsConf.

Active Reload: Sneak Peek: What We Built While You Were At RailsConf

A sneak peek at the Active Reload guys Trac replacement

RSpec 1.0.0

RSpec reaches 1.0.0

/cache_fu - Ruby on Rails Plugins from Err the Blog

Rails memcached plugin

Slides for my RailsConf talk: &quot;Scaling a Rails Application from the Bottom Up&quot;

Jason Hoffman's presentation from RailsConf2007

Harnessing Capistrano

Jamis Buck's presentation from RailsConf2007
next page »
What is this?