3 helpfull functions

August 11, 2007 | In: ruby, tutorials

These are a few functions that I use in every rails project I do so I figured I would pass them along. Perhaps someone will find them useful.

This first one is a function to get a page number for pagination based on start index and result set size.

  def get_page(_start,_limit)
    start = (_start || 1).to_i
    size = (_limit || 25).to_i
    return ((start/size).to_i)+1
  end

This function returns an age based on birth date thats pulled from a DateTime db col.

  def age(birthdate)
    unless birthdate.nil?
      age = Date.today.year - birthdate.year
      if Date.today.month < birthdate.month ||
      (Date.today.month == birthdate.month && birthdate.day >= Date.today.day)
        age = age - 1
      end
      return age
    else
      return 0
    end
  end

This function takes a string and a length and truncates it while also appending … to the end.

  def ellipses(str,length)
    if str.nil?
      return
    else
      return (str.length > length) ? "#{str[0,length]}..." : str
    end
  end
Bookmark and Share
blog comments powered by Disqus

Flickr Pics

13th and washington NYC13th and 9th NYC1st st Jersey CityIMG_2813IMG_2814_2IMG_2816IMG_2815Photo_011908_001Photo_122807_001Photo_121107_001