A Simple Pattern for Ruby's inject method

Posted by admin 24/01/2010 at 14h05

Ruby’s inject is an often misunderstood method, but you would be surprised at how much it can help you clean up your code. I see many developers skipping over this method in favor of the non-injectified way, mainly because they dont get how to use inject properly. So we’ll take a look at some common examples and then you will be able to see the pattern that allows you to take advantage of inject. Let’s take a look at inject’s signature:

enum.inject(initial) {| memo, obj | block } => obj

This method is part of the Enumerable module, so you can use this method on many different types, including Arrays, Hash, Strings and many others. Now, let’s take a look at each part of the signature:

  • initial - this is the initial value that you want to set for the memo
  • memo - this is the accumulator object (the sum variable from your standard array summing function)
  • obj - this is the individual obj from the enumerablized container.
  • block - you should know what this is :D

Alright, now that we know what each piece is, let’s look at some examples and the refactor them with inject.

Example 1

This will be a simple summing example:

sum = 0
(1..30).each do |num|
  sum = sum + num

Now let’s refactor this with inject:

(1..30).inject(0) do |sum, num|
  sum + num

Here, we take the initial value of sum (0) and pass it as the argument to inject, this is the initializer. We then take the variable name sum and use it as the initial argument to the block, this is the memo parameter. num then becomes the enumerated object and we continue as we did in our original each method, but instead of assigning the value of the aggregation to the aggregator, we can just aggregate and ruby will take the value of the last line of the block and assign it to the memo.

Example 2

Let’s take a look at a common Rails example that I see all the time in helpers:

ret = ""
@products.each do |prod|
  ret << content_tag(:li, prod.title)
content_tag(:ul, ret)

Now we refactor with inject:

lis = @products.inject("") do |ret, prod|
  ret + content_tag(:li, prod.title)
content_tag(:ul, lis)

This time we initialize inject with “” and we are aggregating li tags for a nice HTML list. There is a more Ruby way to refactor this which would look like:

content_tag(:ul, nil) do 
  @products.inject("") do |ret, prod|
    ret + content_tag(:li, prod.title)

Now, dont think that you can only use one-liners for your inject methods. They are Ruby blocks, and given all the freedoms that all blocks are given. We could do something like this if necessary:

content_tag(:ul, nil) do 
  @products.inject("") do |ret, prod|
    if prod.active? && prod.is_special?
      ret + content_tag(:li, prod.special_title)
    elsif prod.active?
      ret + content_tag(:li, prod.title)
      ret + content_tag(:li, prod.inactive_title)

One other thing to note, inject’s memo object isn’t just for aggregating, it can be used as a simple container for checks:

success = @products.inject(true) do |ret, prod|
  ret && prod.active?

The above is a way to write the Enumerable#all? method. If you replace && with || you get the any? method.

That’s it for this tip, stay tuned for other refactoring tips with Ruby.

Super InPlace Controls has gone through some upgrades.

We’ve Moved

First and foremost, we have moved the code from google to github.

To install run

script/plugin install git://github.com/flvorful/super_inplace_controls.git

Rails 2.3 Support

Tested with Rails 2.3 and 2.1

Better Jquery Support

We have updated the code to work better with jQuery. Now, in_place_date_selector, uses the jQuery datepicker method if available. JRails is required for jquery support.

Better Validation

Validations were a problem with SIPC, but no longer. Now, if you dont have an error div, SIPC will skip over the rendering of the error box and just add the class “fieldWithError” to the proper input tag.

Overall cleanup

Cleaned up the code in general and made it less brittle.

Check out the demos and the docs at our Open Source Site and stay tuned for some new plugins we’ve been working on.


SuperInPlaceControls: A new rails plugin from Flvorful

Posted by admin 10/12/2007 at 17h12

We just finished up our newest plugin: SuperInPlaceControls.

This is meant as a drop in replacement for the current in_place_edit_for method that was recently moved into a plugin. SuperInPlaceControls works with Rails 2.0, validations, and empty fields.

Check out the SuperInPlaceControls page for more info, demos, examples and docs.

Have fun.


New Rails Plugin - Acts As Noteable

Posted by admin 10/06/2007 at 13h51

So I was at work and I needed to add notes to multiple models in the same project (before i only had to worry about one model with notes, so it was pretty straightforward). So i bit down and knocked out this little plugin.

I borrowed heavily from Acts As Rateable by Juixe


Run the following command:

script/plugin install http://acts-as-noteable.googlecode.com/svn/trunk/acts_as_noteable

The install will try and copy some scripts over, this works sometimes. If you get a rake error do the following:

  1. cd vendor/plugins/acts_as_noteable
  2. rake update_scripts

Create a new rails migration:

script/generate migration add_notes_to_project

and add the following self.up and self.down methods

    def self.up
        create_table "notes", :force =&gt; true do |t|
            t.column "from", :string, :limit =&gt; 50, :default =&gt; "" 
            t.column "body", :text, :default =&gt; "" 
            t.column "created_at", :datetime, :null =&gt; false 
            t.column "noteable_id", :integer, :default =&gt; 0, :null =&gt; false 
            t.column "noteable_type", :string, :limit =&gt; 15, :default =&gt; "", :null =&gt; false 

    def self.down
        drop_table :notes 

(one day i’ll add a migration script to the plugin to automatically add this :) )

After that run “rake migrate” to create the table.

Now all you need to do is call acts_as_noteable in your model:

class Model &lt; ActiveRecord::Base

Now your model is notable, but that’s not all.

For only 19.95 you get a Helper method to help you create a nice form. Ok, so i am not actually charging, but whatever.

Here’s how the helper works.

In the view you want to display notes in put the following:

&lt;%= display_notes(object) %&gt;

This will create a div filled with the note entries for the object and a AJAX form to add new notes to the object as well as delete notes from the object. The add and delete methods are stored in the notes_controller.rb that gets copied over into your app/controllers directory.

The full implementation for this method is:

&lt;%= display_notes(obj, partial_name = "notes/note", controller_name = "notes") %&gt;

I added the partial name and controller name in case you have multiple controllers in different folders, this way you can display notes for objects whose controllers are buried deep in a folder.

Example: I have an “admin” folder for all the backend stuff and I needed a way to reference the notes controller from different places, otherwise RAILS will assume you are trying to reference a controller from the current folder your in.

After you have called display_notes, your done.

Note** This plugin has not been tested with Rails 2.0 yet



Rescuing Ruby

Posted by admin 11/08/2007 at 19h07

Now, before anyone goes crazy, this article has nothing to do with saving ruby from something, i just couldnt think of a better title. We will be talking about rescue and some cool tricks that can be done with it.

As most of you vets know, every thing in Ruby is an object. What most noobs dont realize is how powerful that can be and how concise your code can become. Of course, the flip side of that problem is what i call, newbie-come-expert. It’s basically the stage in a noob’s study of a language where they think they know enough to write really cool software. What actually happens is they end up with code like this:

@objects.map {|e| [e.id, e.title]}.sort {|a, b| a.last <=> b.last}.map {|e| e.join(" ")}.join("\n")


Dont worry noobs, everyone does it. I’m still trying to undo it from some of my older code.

Anyway, my point is, sometimes Ruby’s dynamicism (say that 3 times fast) can lead to messy code so use this tip wisely.

On to the actual tip.

So, like I said before, EVERYTHING in Ruby is an object, even the remains of a rescue clause or an inline rescue which is what we will be playing with here.

How many of you have done this:

@person = Person.find(some_id)

only to get the following error:

ActiveRecord::RecordNotFound: Couldn't find Person with ID=22

It’s pretty annoying, mainly because this type of thing could easily happen in a live app. A user goes to find something that isnt there. One way around it is to have a rescue at the end of the method, but what if you have multiple finds that could throw errors? What if you still need to be able to proceed with whatever you are doing, even if the object isnt found?

This is where inline @rescue@’s can help.

Now you can pull all of your finds together and end them with a rescue.

Let’s say you had the following code:

@person = Person.find(params[:id])
@employee = Employee.find(params[:employee_id])

Now, if either of these finds fail, you will get an error. Instead of rescuing the entire method, you can resuce each statement and make the return value nil and check for nil like you normally would.

New code:

@person = Person.find(params[:id]) rescue nil
@employee = Employee.find(params[:employee_id]) rescue nil

Now when you cant find the ID, it will rescue and just set the variables to nil and move on.

You can also set the rescues to another default datatype instead of nil.

Now, you may be saying, “Wait, why would a user need to enter an id”. Well, one example is an order id, or a tracking number. Anyway, I have run across this a couple of times and thought i’d write something about it.

until next time.