Flowdock

Notes posted by patrickberkeley

RSS feed
October 1, 2009
0 thanks

Update attributes on mulitple models

Updates attributes on multiple models, saves each if validations pass.

def update_multiple

  @items = Item.find(params[:item_ids])
  @items.each do |item|
    item.attributes = params[:item].reject { |k,v| v.blank? }
  end
  if @items.all?(&:valid?)
    @items.each(&:save!)
    flash[:notice] = "Updated items!"
    redirect_to items_path
  else
    flash[:notice] = "Please enter valid data."
    render :action => 'edit_multiple'
  end
end
September 14, 2009
6 thanks

Pluralize Without Count

Helper method that returns the word without the count.

application_helper.rb

def pluralize_without_count(count, noun, text = nil)
  if count != 0
    count == 1 ? "#{noun}#{text}" : "#{noun.pluralize}#{text}"
  end
end

Example usage:

_form.html.erb

<%= pluralize_without_count(item.categories.count, 'Category', ':') %>
September 6, 2009
0 thanks

Add last_week to core_extensions

If you want to implement last_week as posted by Mange, save it as:

lib/core_extensions.rb

class Date
  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
end

And add to:

config/environment.rb

require 'core_extensions'
March 27, 2009
4 thanks

Hour with/without preceding zero

One gotcha is the difference between the hour in 12 hour time with and without a preceding zero. In some fonts they look the same.

With preceding zero (capital I)

Time.now.strftime("%I:%M") # => 05:21

Without preceding zero (lowercase L)

Time.now.strftime("%l:%M") # => 5:21
March 27, 2009
0 thanks

Hour with/without preceding zero

One gotcha is the difference between the hour in 12 hour time with and without a preceding zero. In some fonts they look the same.

With preceding zero (capital I)

Time.now.strftime("%I:%M") # => 05:21

Without preceding zero (lowercase L)

Time.now.strftime("%l:%M") # => 5:21
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)