Flowdock

Recent notes

RSS feed
November 26, 2008
10 thanks

Types array shorthand

You can have respond_to blocks that look like this:

respond_to do |format|
  format.html
  format.xml
end

Here each individual format doesn’t receive a block and so Rails automatically tries to render the appropriate view for the mime type (e.g. action.html.erb, action.xml.erb or as a last resort action.erb)

You can do exactly the same thing by passing an array of Mime types to respond_to like this:

respond_to(:html, :xml)
November 24, 2008 - (<= v2.2.1)
7 thanks

Full List of Supported Formats

With a sample date of December 25th, 2008, at 14:35:05:

:db           # => 2008-12-25 14:35:05
:number       # => 20081225143505
:time         # => 14:35
:short        # => 25 Dec 14:35
:long         # => December 25, 2008 14:35
:long_ordinal # => December 25th, 2008 14:35
:rfc822       # => Thu, 25 Dec 2008 14:35:05 +0000
November 21, 2008 - (>= v2.0.0)
0 thanks

Installation

Install the plugin by typing

script/plugin install auto_complete

Remember to restart webservice :)

November 20, 2008
1 thank
November 20, 2008 - (<= v2.1.0)
0 thanks

Problematic :scroll option

If you use the :scroll => true option, note that at http://github.com/madrobby/scriptaculous/wikis/sortable-create it says:

“If you want your sortable list to be scrollable, wrap the list in a div and set the div to scrollable as apposed to making the ul element scrollable. Also, in IE you must set “position:relative” on the scrollable div.”

November 19, 2008
9 thanks

Formatting options

Readable strftime

%a - The abbreviated weekday name (“Sun”)

%A - The full weekday name (“Sunday”)

%b - The abbreviated month name (“Jan”)

%B - The full month name (“January”)

%c - The preferred local date and time representation

%d - Day of the month (01..31)

%H - Hour of the day, 24-hour clock (00..23)

%I - Hour of the day, 12-hour clock (01..12)

%j - Day of the year (001..366)

%m - Month of the year (01..12)

%M - Minute of the hour (00..59)

%p - Meridian indicator (“AM” or “PM”)

%S - Second of the minute (00..60)

%U - Week number of the current year, starting with the first Sunday as the first day of the first week (00..53)

%W - Week number of the current year, starting with the first Monday as the first day of the first week (00..53)

%w - Day of the week (Sunday is 0, 0..6)

%x - Preferred representation for the date alone, no time

%X - Preferred representation for the time alone, no date

%y - Year without a century (00..99)

%Y - Year with century

%Z - Time zone name %% - Literal “%’’ character t = Time.now t.strftime(“Printed on %m/%d/%Y”) #=> “Printed on 04/09/2003” t.strftime(“at %I:%M%p”) #=> “at 08:56AM”

November 18, 2008
8 thanks

Pop for last, Shift for first

If you want to pop the first element instead of the last one, use shift .

November 16, 2008 - (>= v2.1.0)
11 thanks

Application Helper for Fading Flash Messages

A simple helper method for showing the flash message. Includes optional fade in seconds (view needs javascript_include_tag defaults if you desire fade effect):

def show_flash_message(options={})
  html = content_tag(:div, flash.collect{ |key,msg| content_tag(:div, msg, :class => key) }, :id => 'flash-message')
  if options.key?(:fade)
    html << content_tag(:script, "setTimeout(\"new Effect.Fade('flash-message');\",#{options[:fade]*1000})", :type => 'text/javascript')
  end
  html
end

simply call in your views then using:

<%= show_flash_message(:fade => 4) %>
November 16, 2008
1 thank

:select multiple fields

it might be obvious or not:

Task.find :all, :select => "name, members"
November 14, 2008
0 thanks
November 12, 2008
6 thanks

Another Example

Do not mistakenly pass class_name as a key/value pair (Hash form). You will get an error including the text ‘class or module needed’. It should look like this:

serialize :some_array, Array

Or, perhaps clearer would be:

serialize(:some_array, Array)

That may seem obvious, but it is common to be in the habit of passing things as a key/value pair.

November 12, 2008
1 thank

Ajax form

<% form_remote_tag :url => { :action => “analyze”}, :update => “result” do %>

  <%= select_tag 'company_id', options_for_select([]) %><br/>
  <%= text_area_tag :text, nil, { :cols => 100, :rows => 10 }%><br/>
  <%= submit_tag "Analyze", :disable_with => "Please wait..." %>
<% end %>
<div id="result"></div>
November 11, 2008
4 thanks

:use_route to force named routes in url_for

If you are using a plugin or library that calls url_for internally, you can force it to use a particular named route with the :use_route key. For instance, calling:

url_for(:controller => 'posts', :action => 'view', :id => post, :use_route => :special_post)

will have the same effect as:

special_post_url(post)

Naturally, this is much more verbose if you’re calling it directly, but can be a lifesaver if url_for is being called inside another method (e.g. will_paginate).

November 7, 2008
3 thanks

Re: Using a Loading Graphic

You probably want to be using :complete, not :loaded, to execute Javascript when an Ajax request has finished. See: http://prototypejs.org/api/ajax/options

November 7, 2008 - (v1.0.0 - v2.1.0)
0 thanks

Using your model's connection

It’s possible to execute raw SQL over the currently established connection for a model.

You may configure Rails to use different databases for different models. To make sure you are querying the correct database you may do the following:

MyModel.connection.execute("UPDATE `my_models` SET `beer`='free' WHERE 1")
November 7, 2008
3 thanks

Common options

“Common options” mentioned here is default PrototypeHelper options documented in link_to_remote

This means you can use :loading, :loaded, :failure, :success, etc in observe_field.

November 7, 2008
2 thanks

Parsing YAML from a POST request

When building a REST server which should accept YAML there are several things to take into consideration.

First of the client should tell the server what type of data it is going to send. This is done via the Content-Type header (which is NOT only a response header as opposed to what the RESTful Web Services book from O’Reilly made us believe).

Second the server application should know how handle the body of the POST request. Placing the following line in your environment.rb:

ActionController::Base.param_parsers[Mime::YAML] = :yaml

This registers the YAML parser. Smooth sailing from here on!

November 7, 2008
3 thanks

Add spacer template

<%= render :partial => “product”, :collection => @products, :spacer_template => “product_ruler” %>

November 6, 2008 - (v1_8_6_287)
1 thank

Missing Documentation

Returns false if obj <=> min is less than zero or if anObject <=> max is greater than zero, true otherwise.

3.between?(1, 5)               #=> true
6.between?(1, 5)               #=> false
'cat'.between?('ant', 'dog')   #=> true
'gnu'.between?('ant', 'dog')   #=> false
November 6, 2008
4 thanks

current_url

exact url from browser window:

def current_url
  url_for :only_path=>false,:overwrite_params=>{}
end
November 6, 2008
1 thank

Compiling mysql gem in Leopard with MacPorts MySQL

Needs architecture and reference to mysql_config:

sudo env ARCHFLAGS="-arch i386" gem install mysql -- \
--with-mysql-config=/opt/local/lib/mysql5/bin/mysql_config
November 5, 2008
2 thanks

Rendering YAML

When you want to render XML or YAML you can use

render :xml, some_object.to_xml 

or

render :json, some_object.to_json

However there is no equivalent for YAML. What you can do is render just plain text with a correct content-type:

render :text => some_object.to_yaml, :content_type => 'text/yaml'

The content_type is debatable but this seems to be the most standard.

November 5, 2008
0 thanks

re: james' note incorrect

kieran is correct, my note is incorrect, it was not meant for ActionMailer::Base

November 5, 2008 - (v1.0.0 - v2.1.0)
1 thank

james' note incorrect

The render method in ActionMailer is infact a private method, in all versions (including the new Rails 2.2).

However, spectators note about @template works well. Thanks.

November 5, 2008
0 thanks

RERE: 1 render definition for many actions (cleaner)

@arronwashington. Ah, so that’s the motivation for using default_render, thanks for clearing that up, thanks :)

November 4, 2008
2 thanks

RE: 1 render definition for many actions (cleaner)

Hi James,

Unfortunately that doesn’t work if you use the

@zombies 

variable in the rendered template, which is why default_render was added as a patch AFAIK. :)

before_filter is called too soon, after_filter is called after an attempt at rendering is made, so default_render is the only option for this as far as I know.

November 4, 2008
0 thanks

re: Specifying :include no longer necessarily joins the association

I have seen how :include does not nessisarily perform a join during that SQL query, if you need the join to occur then, rather then tricking AR (“forcing”), use :joins instead of :include to ensure the joins occur.

November 4, 2008 - (v1.0.0 - v2.1.0)
1 thank

1 render definition for many actions (cleaner)

@arronwashington, you can just call render rather then using instance_eval to overwrite default_render, for example:

before_filter :render_filter, :only => [:zombies, :cool_zombies]

def zombies
  @zombies = Zombie.find(:all)
end

def cool_zombies
  @zombies = Zombie.find(:all, :conditions => { :eats_humans => false, :is_hippie => true })
end

protected

def render_filter
  # without instance_eval or overwriting default_render
  render :template => 'zombies/all'
end
November 4, 2008
0 thanks

1 render definition for many actions.

Overriding default_render in especially useful when you have many actions that all render the same thing.

before_filter :render_filter, :only => [:zombies, :cool_zombies]

def zombies
  @zombies = Zombie.find(:all)
end

def cool_zombies
  @zombies = Zombie.find(:all, :conditions => { :eats_humans => false, :is_hippie => true })
end

protected

def render_filter
  instance_eval do
    def default_render
      render :template => 'zombies/all'
    end
  end
end
November 2, 2008
2 thanks

params hash gets the model id automatically

The params hash gets automatically populated with the id of every model that gets passed to form_for. If we were creating a song inside an existing album:

URL:/albums/209/songs/new
form_for [@album, @song] do |f| 
  ...
  f.submit "Add"
end

The params hash would be:

params = {"commit"=>"Add", 
          "authenticity_token"=>"...",
          "album_id"=>"209",
          "song"=>{"song_attributes"=>{...}}
          }

So, in the songs_controller you could use this album_id in a before_filter:

before_filter :find_album
protected
def find_album
  @album = Album.find(params[:album_id])
end

If you only did this:

form_for @song do |f| 

You would get this params hash:

params = {"commit"=>"Add", 
          "authenticity_token"=>"...",
          "song"=>{"song_attributes"=>{...}}
          }