Flowdock

Recent notes

RSS feed
February 24, 2009 - (>= v2.2.1)
5 thanks

ATM does not work in Rails 2.3 Edge

add to test/spec_helper to make it work again…

#spec_helper / test_helper
include ActionController::TestProcess
February 24, 2009
2 thanks

Test if one array includes the elements of another v2

Maybe a bit more readable way to write the previous snippet would’ve been

puts "yay" if [1, 2, 3].all? { |i| (1..9).include?(i) }
# => "yay"

puts "nope" if [1, 2, 3, 'A'].any? { |i| not (1..9).include?(i) }
# => "nope"
February 24, 2009
0 thanks

Test if one array includes the elements of another

Recently I’ve written this little snippet:

puts "yay" if [1, 2, 3].each {|i| break unless (1..9).to_a.include?(i)}
# => "yay"

puts "nope" unless [1, 2, 3, 'A'].each {|i| break unless (1..9).to_a.include?(i)}
# => "nope"
February 24, 2009
0 thanks

Validate an optional URL field

Let’s say that you have an optional URL field to one of your models and you want to validate the URL. You can accomplish this by using the URI library:

require 'uri' # Put this at the beginning of your model file

validates_each :url, :allow_blank => true do |record, field, value|
  begin
    valid = (URI.parse(value).scheme =~ /https?/)
  rescue URI::InvalidURIError
    valid = false
  end
  record.errors.add field, "not a valid url" unless valid
end

If you want to add even more testing in there, just go ahead. For now, we just check that the link is to a HTTP resource, but you might have other requirements. This will allow stuff like “http://example” since “example” might be a valid intranet domain. If you want to check for a TLD in there, you can do so with a simple regexp.

For more information about the URI library, check out http://apidock.com/ruby/URI/

February 23, 2009 - (<= v2.2.1)
1 thank

You can't have many :through with habtm

Imagine the following

a has_many b
b has_and_belongs_to_many c
a has_many c :through => b

a.b works fine

b.c works fine

a.c throws an error!

has_many :through where the through association is a habtm is not supported in Rails. The error is:

ActiveRecord::HasManyThroughSourceAssociationMacroError: Invalid source reflection macro :has_and_belongs_to_many for has_many :stories, :through => :subcategories. Use :source to specify the source reflection

Specifying the source reflection still won’t help you though, because this kind of has_many :through isn’t supported at all.

February 23, 2009 - (>= v2.0.0)
4 thanks

Nested with_options

You can nest with_options blocks, and you can even use the same name for the block parameter each time. E.g.:

class Product
  with_options :dependent => :destroy do |product|
    product.with_options :class_name => 'Media' do |product|
      product.has_many :images, :conditions => {:content_type => 'image'}
      product.has_many :videos, :conditions => {:content_type => 'video'}
    end

    product.has_many :comments
  end
end
February 23, 2009
2 thanks

Check if value is included in array of valid values

If you want to check the value of an attribute using an array of valid values, the array has to be defined before the validation, so

validates_inclusion_of :name, :in => VALID_NAMES
VALID_NAMES = %w(Peter Paul Mary)

won’t work, but

VALID_NAMES = %w(Peter Paul Mary)
validates_inclusion_of :name, :in => VALID_NAMES

will.

February 22, 2009
3 thanks

CAUTION! :frequency option description is misleading

To use event-based observer, don’t supply :frequency param at all. :frequency => 0 causes JS error.

Use this option only if time-based observer is what you need.

February 20, 2009
5 thanks

Static and dynamic attachments

You can attach static files directly:

attachment :content_type => "image/jpeg", :body => File.read("someimage.jpg")

and you can also define attachments dynamically by using a block:

attachment "text/csv" do |a|
  a.body = my_data.to_csv
end
February 18, 2009
4 thanks

Turn off for individual controllers/actions

To disable protection for all actions in your controller use skip_before_filter:

skip_before_filter :verify_authenticity_token

You can also pass :only and :except to disable protection for specific actions, e.g:

skip_before_filter :verify_authenticity_token, :only => :index
February 17, 2009
4 thanks

Date_select with assert_valid_keys

If you are using date_select with assert_valid_keys you have to allow 3 parameters named field(1i), field(2i) and field(3i).

For example with field

date_select("post", "written_on")

You have to allow following fields:

params[:post].assert_valid_keys( 
  'written_on(1i)', 'written_on(2i)', 'written_on(3i)'
)
February 17, 2009
7 thanks

Usage examples

Basic usage:

User.should_receive(:find).with(:all, anything).and_return("hello world")

Now:

User.find(:all, :conditions => "foo")  #=> "hello world"

But you can also use blocks for more complex matching logic. For example:

User.should_receive(:find) { |*args|
  if args.size == 2
    "received two arguments"
  else
    "something else"
  end
}.at_least(:once)

Now:

User.find(:all, :conditions => "bar")  #=> "received two arguments"
User.find(5)                           #=> "something else"

Of course normally you’d return mocks instead of strings.

February 17, 2009
9 thanks

Empty elements

If you want to output an empty element (self-closed) like “br”, “img” or “input”, use the tag method instead.

February 17, 2009
2 thanks

Remember to sanitize name

While useful when in need of richer markup inside a link, the name parameter isn’t sanitized or escaped and thus should be escaped when its content can’t be guaranteed to be safe.

E.g.

link_to(url, url)

may cause problems with character entities if url contains ampersands.

Correct usage
link_to(h(url), url)

This applies to all dynamic content.

February 17, 2009
1 thank

See column

See the end part of the docs on column for example uses.

February 16, 2009
1 thank

See max

See max for comments and more usage examples.

February 16, 2009
2 thanks

Capping values

This method is very useful when you want to cap values:

# minimum ≤ value 
value = [input.to_i, minimum].max

# value ≤ maximum
value = [input.to_i, maximum].min

# minimum ≤ value ≤ maximum
value = [ [input.to_i, minimum].max, maximum ].min

# Practical example: Make sure destination is within container
destination.x = [ [current.x + current.velocity.x, 0].max, container.width  ].min
destination.y = [ [current.y + current.velocity.y, 0].max, container.height ].min
February 16, 2009
5 thanks

Usage example

Some examples:

# Remove even numbers
(1..30).reject { |n| n % 2 == 0 }
# => [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29]

# Remove years dividable with 4 (this is *not* the full leap years rule)
(1950..2000).reject { |y| y % 4 != 0 }
# => [1952, 1956, 1960, 1964, 1968, 1972, 1976, 1980, 1984, 1988, 1992, 1996, 2000]

# Remove users with karma below arithmetic mean
total = users.inject(0) { |total, user| total += user.karma }
mean = total / users.size
good_users = users.reject { |u| u.karma < mean }
February 16, 2009
1 thank

Reverse of this

If you want to do the reverse of this, e.g. go from a specific date and back to a certain day of the previous week, you can implement it like this:

def last_week(day = :monday)
  days_into_week = { :monday => 0, :tuesday => 1, :wednesday => 2, :thursday => 3, :friday => 4, :saturday => 5, :sunday => 6}
  result = (self - 7).beginning_of_week + days_into_week[day]
  self.acts_like?(:time) ? result.change(:hour => 0) : result
end

If you do not want to make your own method of this, but just want to do it in a regular chaining of date methods (like Date.today.next_year.at_midnight), you can do it like the following:

(date - 7).next_week(:tuesday) # Tuesday, last week

Please note that you just need to subtract 7 if you want to move back a week. Only use these methods if you want to go to a specific day of the week.

February 16, 2009
1 thank

Reverse naming

The reverse of this is last_month and not previous_month, like one might believe from the naming.

February 16, 2009
1 thank

Reverse naming

The reverse of this is last_year and not previous_year, like one might believe from the naming.

February 15, 2009
0 thanks

use #collect instead of #each

The earlier reminder to use #collect instead of #each applies regardless of whether the tag is nested or not.

This is counterintuitive, as #collect returns an array of strings of HTML tags, but ActionView renders it properly.

February 14, 2009
1 thank

Clear and simple rescue

noxyu3m, your code is rescuing all exceptions, not just ActiveRecord::RecordInvalid.

I think this syntax is a bit more clear than using the global variable.

def create
  @model = Model.new(params[:model)
  @model.save!
rescue => err                          # rescues all exceptions
  logger.error(err.to_s)
end
February 14, 2009
0 thanks

Simple rescue

Take it easy:

def create
  @model = Model.new(params[:model)
  @model.save!
rescue
  logger.error(!$.to_s)
end

Global variable !$ refers to the Exception object.

February 13, 2009
1 thank

throws exception

when use use Model.find([1,2,3,4])

throws exception if no record exists with any of this ID

February 13, 2009
3 thanks

New test syntax

You can use either one and even mix in the same test case if you want:

class Test < Test::Unit::TestCase
  # old way to define a test method (prefix with test_)
  def test_should_be_valid_without_content
    assert Comment.new.valid?
  end

  # new way to define a test
  test "should be valid without content" do
    assert Comment.new.valid?
  end
end
February 12, 2009
4 thanks

Real life use

If you’re wondering what the base64 format is used for, here are some examples:

  • HTTP Basic authentication: encode your username and password as one string, and add it as a header of an HTTP request. When a page requiring basic authentication gets called from a browser it results in a generic Username/Password dialog from that browser. See also http://en.wikipedia.org/wiki/Basic_access_authentication

  • Encode the binary content of images to base64 and embed it in XML documents, for example in web services

  • For more information see http://en.wikipedia.org/wiki/Base64

Just note that the encoded (character) data is about 30% larger than un-encoded (binary) data.

February 12, 2009
0 thanks

using collection=objects

It will fire one insert query per new record