NinjaCipher:-*-:ro60

3 helpfull functions

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
Del.icio.us Digg BlinkList Furl Ma.gnolia Reddit Spurl

2 Responses to “3 helpfull functions”

  1. lukemelia Says:

    Could come in handy, thanks. For the last one, you
    could use TextHelper#truncate, too. See http://api.rubyonrails.com/classes/ActionView/Helpers/TextHelper.html#M000621

    Cheers,
    Luke

  2. mattd Says:

    Absolutely right… I guess thats why it pays to read the
    api docs :)

Leave a Reply

You must be logged in to post a comment.