Flowdock

Recent notes

RSS feed
September 22, 2008
0 thanks

Different Options

The docs don’t give any detail to what options are available, so I dug around and I think the only to options are :prompt and :include_blank

September 21, 2008 - (>= v2.1.0)
0 thanks

Test Example

UserMailerTest Example

class UserMailerTest < ActionMailer::TestCase
  tests UserMailer

  def test_welcome_mail
    user = users(:quentin)

    MyMailer.deliver_welcome_email
    assert !ActionMailer::Base.deliveries.empty?

    sent = ActionMailer::Base.deliveries.first
    assert_equal [@user.email], sent.to
    assert_equalexpected subject”, sent.subject
    assert sent.body =~ /^Welcome to my App/
    assert sent.body =~ /^Username: #{@user.login}$/
    assert sent.body =~ /^Password: [a-z0-9]{10}$/i
  end
end

This example is a modified version of the one in this blog post:

http://sablog.com/archives/2006/03/14/how-to-test-actionmailer-in-ruby-on-rails

September 21, 2008
1 thank

resourceful

auto_discovery_link_tag :atom, movies_url(:format=>‘atom’), :title=>‘New movies’

to produce the feed:

respond_to do |wants|
  wants.html
  wants.atom {render :action=>'index',:layout=>false}
end
September 21, 2008
0 thanks

Better Description

This is really a bitshift left.

September 19, 2008 - (v2.1.0)
3 thanks

:expires_in option

If you need :expires_in functionality in Rails 2.1, you can use this plugin:

http://github.com/nickpad/rails-caches-action-patch/tree/master

September 18, 2008
1 thank

unobstrusive label tag

just use

label_tag('a_a','a_a') 

and it works, just not ment for pure decorative labels :)

September 17, 2008
4 thanks

Turn layout off with render

Thats awkward, but the code below does not turn layout off:

render :action => "short_goal", :layout => nil

you must use false

render :action => "short_goal", :layout => false
September 17, 2008
0 thanks

removes underscores -> do not use for images etc

example

#does not work
label_tag('aa'+image_tag('x_x.gif')) 
September 16, 2008
7 thanks

print standard-looking messages during migration

Within a migration file you can use the say_with_time method to print out informational messages that match the style of standard migration messages. See the say method also.

say_with_time "migrate existing data" do
  # ... execute migration sql ...
end
#=> "-- migrate existing data"
#=> "   -> 0.0299s"
September 16, 2008
1 thank

print standard-looking messages during migration

Within a migration file you can use the say method to print out informational messages that match the style of standard migration messages. The say_with_time method is also pretty great.

say "migrate existing data"
  #=> "-- migrate existing data"
# ... execute migration sql ...
say "updated all records", :subitem
  #=> "   -> updated 5 records"
September 15, 2008
4 thanks

:null => false

To not allow a column to have a NULL value, pass :null => false. Seems silly, but that’s it.

September 15, 2008 - (<= v2.1.0)
8 thanks
September 13, 2008
0 thanks

Examples

Some usages:

Code example

Time.new.months_ago(1) # => Wed Aug 13 10:56:32 -0300 2008

Date.today.month_ago(7) # => Qua, 13 Fev 2008

Time.new.months_ago(1).to_s(:db) # => “2008-08-13 10:57:56”

September 12, 2008
24 thanks

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”

September 11, 2008 - (v1.2.0 - v2.1.0)
4 thanks

Information on 'ModelName.transaction'

If you are looking for information about:

ModelName.transaction do
  ...
end

or

transaction do
  ...
end

see ActiveRecord::Transactions::ClassMethods

September 11, 2008 - (v1.2.0 - v2.1.0)
4 thanks

Information on 'ModelName.transaction'

If you are looking for information about:

ModelName.transaction do
  ...
end

or

transaction do
  ...
end

see ActiveRecord::Transactions::ClassMethods

September 11, 2008
1 thank

CSS columns

You can also use this in a partial to create blocks of content into columns without setting a fixed height. This one is two columns.

.clear { clear: both;}
.block { float:left;width:200px;}

<div class="block">

<p>Content Item</p>

</div>
<%= cycle("", "<div class=\"clear\"></div>") -%>
September 10, 2008
0 thanks

Actual superclass

This class’s actual superclass is Net::HTTPRequest, for some reason that isn’t linked in here.

September 10, 2008
4 thanks

Be careful with overriding dynamic attribute based finders

don’t try something like this:

class Foo < ActiveRecord::Base
  def self.find_by_bar(*args)
    foo = super(*args)
    raise SomeCustomException unless foo
    foo
  end
end

In newer versions of rails, method_missing defines find_by_bar when you first use it. By calling super, you’re triggering method_missing and overwriting your custom definition! It will work the first time then break! Manually write the call to find!

September 9, 2008 - (<= v2.1.0)
4 thanks

Reset a form

To reset a form easily you can do the following:

page["formid"].reset
September 5, 2008
6 thanks

Custom collection local variable name

Regarding the previous note from hoodow about using :variable_name to create a custom local variable name when rendering a collection with a partial, the argument should be :as instead of :variable_name, so:

render :partial => “video_listing”, :collection => @recommendations, :as => :video

September 5, 2008
3 thanks

Require 'strscan'

To use the StringScanner class,

require 'strscan'
September 5, 2008 - (v1.0.0 - v2.0.3)
3 thanks

This method has moved

To help anyone else looking, this method is now on the ActionView::Template class.

September 4, 2008
4 thanks

Testing protected controllers

When testing controllers which are protected with #authenticate_or_request_with_http_basic this is how you can supply the credentials for a successful login:

@request.env["HTTP_AUTHORIZATION"] = "Basic " + Base64::encode64("username:password")

Must be set before the request is sent through #get or whatever method.

September 3, 2008
1 thank

Creating additional cache stores

This method can be used to create additional cache stores for your application:

# creates a new Memory Store
mem_store = ActiveSupport::Cache.lookup_store
# creates a new MemCache Store
mem_cache_store = ActiveSupport::Cache.lookup_store :mem_cache_store, 'localhost:11212', :namespace => 'other_stuff'

The method takes the same arguments as the cache_store config. For more information about that go to ActionController::Caching.

September 2, 2008
5 thanks

Useful in migrations

The most common usage pattern for this method is probably in a migration, when just after creating a table you want to populate it with some default values, eg:

class CreateJobLevels < ActiveRecord::Migration
  def self.up
    create_table :job_levels do |t|
      t.integer :id
      t.string :name

      t.timestamps
    end

    JobLevel.reset_column_information
    %w{assistant executive manager director}.each do |type|
      JobLevel.create(:name => type)
    end
  end

  def self.down
    drop_table :job_levels
  end
end
September 1, 2008 - (>= v2.1.0)
5 thanks

ActiveRecord::Base.include_root_in_json

From Rails 2.1 onwards, the variable

ActiveRecord::Base.include_root_in_json

affects how the JSON is generated. If this is true (default), then the JSON isn’t like the one above. Instead you’ll get:

konata = User.find(1)
konata.to_json
# => { "user": { "id": 1, "name": "Konata Izumi", "age": 16,
      "created_at": "2006/08/01", "awesome": true}}

(Note the model name is included as a root of the JSON object)

For Rails 2.1 generated projects, you’ll see this in the config/initializers/new_rails_defaults.rb file. You’ll need to set the value to false if you want the old behaviour.

ActiveRecord::Base.include_root_in_json = false
August 29, 2008
10 thanks

Always pass a block

I highly recommend always taking a block and passing it back up the chain if you use alias_method_chain, even if the original method does not. Otherwise you’re keeping anyone later in the chain from adding support for blocks.

http://tech.hickorywind.org/articles/2008/08/29/always-pass-a-block-when-using-alias_method_chain

August 29, 2008
4 thanks

Brazilian Real (R$ 1.200,95)

helper:

def number_to_currency_br(number)
  number_to_currency(number, :unit => "R$ ", :separator => ",", :delimiter => ".")
end