Informatika Mihelac

Articles tagged with tips

May 12 2007 tips 6 comments

Rails in practice - Group records by condition

Often, when it comes to views I have to group records and present it to the user grouped by some condition. For example, I would like to list all news articles grouped by year.

To accomplish this, I find it easiest that records are grouped in a hash, key should be year when article is published and value would be array of objects matching published on these year.

Before, I used custom function that would walk throught all elements of array calling custom block for each member and creating new hash with result value of the block as key and array of elements as value.

Today I discover classify method in Set class that would do just what I need (thanks to Ruby Cookbook for that).

So, the code to group all news articles by year published is:

@groups = NewsArticle.find(:all).to_set.classify {
  |article| article.published_on.year}

and view would be something like these:

<%@groups.each do |year, articles|%>
  <h1><%=year%></h1>
  <%=articles.collect {|a| \"<p>a.name</p>\"}.join%>
<%end%>

Short and sweet. Same method can be used to group anything, names by first letter, products by price range, etc.

December 16 2006 tips 0 comments

Working with dates in Ruby

Ruby has three classes for working with date and time: Date, DateTime which subclasses Date and Time. There is an interesting article why we need all 3 classes, and here are some notes about working with dates:

  • Time.now != DateTime.now && Time.superclass != Date
  • There is no method in Time class to convert object to a Date object, but you can write date = Date.new(time.year, time.mon, time.day). Rails extends DateTime and Time classes which allows to_date and to_time conversions for both classes.
  • Today is Date.today and now it is Time.now, there is no such thing as Date.now but there is Time.today (even I didn’t saw it in RDocs)
  • Tomorrow is Date.today+1, yestrday Date.today-1, to add or substract a month use Date.today >> 1 or Date.today << 1. See also Rails extensions to time class which allows to write things like Date.today.to_time.at_beginning_of_week
  • Date class includes Comparable module which allows us to write some_date.between?(Date.today, Date.today + 7)
  • Time.now.beginning_of_month.to_date.upto( Time.now.next_month.beginning_of_month.to_date-1) {|d| puts d.to_s} would print all days in current month in your Rails application.

Standard Ruby library also includes ParseDate library for parsing dates and returning array of values. Rails use ParseDate.parsedate to create dates so if you need to support input of additional date formats consider extending parsedate. I am not sure why Date.parse does not use ParseDate.parse but have its own implementation.

September 13 2006 tips 6 comments

Parsing european date format in Ruby/Rails

So you have date in european format DD.MM.YYYY. that you want to parse in ruby? Nothing easier, change parsedate method in ParseDate stdlib.

require ('parsedate')
module ParseDate
  class << self
    alias_method :old_parsedate, :parsedate unless
        method_defined?(:old_parsedate)
  end

  def self.parsedate(str)
    match = /(\d{1,2})\.(\d{1,2})\.(\d{2,4})\.?/.match(str)
    return ParseDate.old_parsedate(str) unless match
    [match[3].to_i, match[2].to_i, match[1].to_i, 
     nil, nil, nil, nil, nil] 
  end
end

On Rails, you can include it in environment.rb file with require ('parsedate_patches.rb').

May 09 2006 tips 4 comments

Overriding class methods in Ruby

Class methods in Ruby are methods that work without being tied to any particular object (Java and PHP5 have static methods for similiar purpose). Class methods are distinguished from instance methods by placing the class name and a period in front of the method name. One thing that may not be obvious if you want to inherit class method is how to call equally named class method from parent class.

If you try to use super.class_method_name it would not work. That’s because class_method_name is class method and not instance method and as such it does not exists in object. Fortunately, classes in Ruby are objects too and you can interact with class like you interact with any other objects.

Enough talking, here is example:


class User
  def User.columns
    "name,email" 
  end
end

class Customer < User
  def Customer.columns
    self.superclass.columns + ",saldo" 
  end
end

puts Customer.columns # << name,email,saldo
March 31 2006 tips 9 comments

Ruby / Rails alternative to PHP print_r() and var_dump()

Both PHP functions provides information about a variable passed as argument. It is often used in development to get quick and human-readable info about array or object. If you are using Rails you can use DebugHelper’s debug(object) helper function. Note that helpers are available only in views. In controllers, models and other Ruby code you can use ‘puts YAML::dump(object)’ method to get readable info about object.

About

I am Bojan Mihelac and this blog is dedicated to share code, thoughts, tools and advices I came up with while working in Informatika Mihelac.

Contact: bmihelac@mihelac.org

RSS feedSubscribe to RSS Feed