Tuesday, December 30, 2008

Using line - wrapping after specified limit.

Following method is useful to display line with wrapping after specified limit. So that if you give a limit to 50, then it will insert '
' after 50 characters. Also, it will not break line from middle of any word. So after using this method, you can provide justification method to display text block properly.

Just pass a paragraph to display as 'par' and also provide a limit as 'length'.

def line_wrapping_after_limit(par, length)
    b = []
    res = []
    if par.length > length
      a = par.split(' ')
      len = 0
      0.upto(a.length-1) do |i|
        temp = a[i]
        while(temp.length > length)
          res << (temp[0, length-1] + "-").to_s
          temp = temp[length-1, a[i].length]
        end
        b << (temp + " ")
        len += temp.length + 1
        tot_len = i.eql?(a.length-1) ? len : len + a[i+1].length
        if(tot_len > length)
          b.join('')
          res << (b.to_s)
          len = 0
          b = []
        end
      end
      b.join('')
      res << (b.to_s)
      res.join("<\br/>

")

    else
      par
    end
  end

No comments:

Post a Comment