Flowdock

Recent notes

RSS feed
December 29, 2008 - (v2.2.1)
1 thank

Deprecation warning for using options without hash

As of Rails 2.2.0, truncate gives a Deprecation warning if you don’t use a hash for the options. Ex:

The old way

truncate(project.description, 100, "... Read More")

The warning

DEPRECATION WARNING: truncate takes an option hash instead of separate length and omission arguments.

The new way

truncate(project.description, :ommision => "... Read More", :length => 100)
December 28, 2008
1 thank

i think that's a bit better resourceful approach...

Code example

auto_discovery_link_tag :atom, formatted_movies_url(:atom), :title=>'New movies'
December 24, 2008 - (>= v2.2.1)
5 thanks

uninitialized constant ActionView::Base::CompiledTemplates::TimeZone

If you get this error, you need to use ActiveSupport::TimeZone.us_zones instead of TimeZone.us_zones.

Example:

<%= form.time_zone_select(:time_zone, ActiveSupport::TimeZone.us_zones) %>
December 23, 2008
0 thanks

Entries are not standalone!

The entry Pathnames consist solely of leaf filenames, so they’re not directly useable in filesystem operations like “open” or “directory?”. To create a useable Pathname, append the entry onto the directory you’re iterating over.

Also keep in mind that the iteration includes the magic entries “.” and “..”, which you probably want to skip. (Is this true on Windows too?)

The #children method doesn’t have either of these issues, although it’s slightly less efficient since it creates an Array of Pathnames up-front instead of yielding one at a time.

December 23, 2008
0 thanks

Incorrectly named option

The :add_month_number option should be :add_month_numbers

December 18, 2008 - (<= v2.2.1)
0 thanks

Belongs_to, Has_many association

I have a belongs_to, has_many association between manufacturer and modelname. (manufacturer has many modelnames).

In the new modelname page, I have a drop down menu that lists all the manufacturers, so I choose eg Dell, and then in modelname.name field I enter inspiron or what ever. To create that drop down I used:

<%= f.select(:manufacturer_id, Manufacturer.find(:all).collect {|u| [u.name, u.id]}, :prompt => 'Select') %>

The reason that works was explained by fcheung and rsl on #rubyonrails. Thanks:

the form builder basically calls the method whose docs you have read, inserting the appropriate first argument

The object is referenced internally when you call f.whatever. in any of those tags, the object is omitted when used on a form block variable

December 16, 2008 - (v1.0.0 - v2.2.1)
14 thanks

Force initial value

If you want to force an initial value for your text_field which is normally based on your object attribute value, you can use :

text_field :ecard, :sender, :value => 'contact@host.com'
December 12, 2008
7 thanks

acts_as_state_machine named scopes

If you are using the acts_as_state_machine plugin, this will generate all named scopes for your various states.

Place it after the acts_as_state_machine and state declarations.

class Task < ActiveRecord::Base
  acts_as_state_machine :initial => :waiting
  state :waiting
  state :running
  state :finished    

  states.each { |s| named_scope s, :conditions => { :state => s.to_s } }
end

Then doing a Task.waiting will return the corresponding tasks.

December 11, 2008
3 thanks

with resources

/products

current_page?(products_path)

# => true
December 11, 2008 - (>= v1.0.0)
5 thanks

Calling migrations within migrations

It’s very occasionally a wise strategy to call migrations from within other migrations. This is typically done when you are adding a migration that deletes a now-obsolete table.

Let’s say one night when you were drunk or otherwise not thinking straight you did something like this:

class CreateExGirlfriendTexts < ActiveRecord::Migration
  def self(dot)up
    create_table :ex_girlfriend_texts { |t| ... }
  end

  def self(dot)down
    drop_table :ex_girlfriend_texts
  end
end

Oops! You could add this for your “undo” migration the next morning:

class FixDrunkMistake < ActiveRecord::Migration
  def self(dot)up
    CreateExGirlfriendTexts.down
  end

  def self(dot)down
    CreateExGirlfriendTexts.up
  end
end

Now, in the event you decide you really did like that table, you can always get it back easily. Keep in mind this will be made more complicated if your table is modified over multiple transactions.

December 11, 2008
6 thanks

Accessing aggregate methods with :group

You can access aggregate methods (such as SUM, COUNT, etc.) when using a JOIN and GROUP BY query by simply naming the aggregate columns and calling them as methods on the returned objects:

hits_by_page = WebpageHit.all({
  :select => "webpages.*, COUNT(webpage_hit.id) AS view_count",
  :joins => :webpage,
  :group => "webpages.id"
})
homepage_hits = hits_by_page[homepage.id].view_count

The view_count method is added to the Webpage model by this call. Note, however, that this method returns a string, and is not typecasted by Rails.

December 10, 2008
0 thanks

Example

my_instance.connection.clear_query_cache

December 6, 2008
5 thanks

Array expansion in blocks

The syntax can be improved as changing the second parameter of the block (values) and using an array of two variables instead, which will be used by Ruby as the key and value of “array”.

array = [['A', 'a'], ['B', 'b'], ['C', 'c']]

hash = array.inject({}) do |memo, (key, value)|
  memo[key] = value
  memo
end

hash
# => {'A' => 'a', 'B' => 'b', 'C' => 'c'}
December 6, 2008
0 thanks

:cache_path strangeness

I’ve noticed that using an example like this one shown in the docs has some issues with URI escaping:

caches_action :feed, :cache_path => Proc.new { |controller|
     controller.params[:user_id] ?
       controller.send(:user_list_url, controller.params[:user_id], controller.params[:id]) :
       controller.send(:list_url, controller.params[:id]) }
 end

When I do this, the :myroute_url methods return URLs with escaped parameters, as one would expect, but for some reason Rails unescapes these strings by the time it uses them to store the cache blob. This is messing up my cache expiration routines, because they keep track of the escaped versions of the urls that are returned by the routing methods, not the unescaped versions. It would be easier if Rails didn’t do any magic to the string and simply used exactly what you pass to cache_path.

December 3, 2008 - (v2.2.1)
5 thanks

Method doesn't exists

Don’t confuse it with new_record? in ActiveRecord

December 2, 2008
5 thanks

From the official docs

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

Combines the elements of enum by applying the block to an accumulator value (memo) and each element in turn. At each step, memo is set to the value returned by the block. The first form lets you supply an initial value for memo. The second form uses the first element of the collection as a the initial value (and skips that element while iterating).

# Sum some numbers
(5..10).inject {|sum, n| sum + n }              #=> 45
# Multiply some numbers
(5..10).inject(1) {|product, n| product * n }   #=> 151200

# find the longest word
longest = %w{ cat sheep bear }.inject do |memo,word|
   memo.length > word.length ? memo : word
end
longest                                         #=> "sheep"

# find the length of the longest word
longest = %w{ cat sheep bear }.inject(0) do |memo,word|
   memo >= word.length ? memo : word.length
end
longest                                         #=> 5

http://www.ruby-doc.org/core/classes/Enumerable.html

December 1, 2008 - (>= v2.2.1)
1 thank

Upgrading from Rails v2.1 to v2.2

Don’t forget to run

rake gems:refresh_specs

if you vendored any gem plugins under Rails v2.1 to update them with the proper specs.

November 28, 2008 - (>= v2.2.1)
2 thanks

Removed form Rails core

country_select and country_options_for_select were removed from Rails core since 2.2 release, but extracted to plugin. http://github.com/rails/country_select/tree/master/README

Also you could be interested in localized_country_select plugin which uses Rails internationalization framework I18n. http://github.com/karmi/localized_country_select/tree/master/README.rdoc

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
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
9 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.