views:

48

answers:

2

Im trying to achieve the following effect in rails:

If the text is bigger than x characters then make it smaller, the next x characters smaller, the next character smaller, ad infinitum

for example x = 7 would output the following html

Lorem i<small>psum do<small>lor sit<small> amet, <small>consecte
<small>tur adip<small>isicing</small></small></small></small></small></small>

and the css would be small {font-size: 95%}

What is an elegant way to achieve this?

+2  A: 

hm. maybe some helper with some recursion?

def shrink(what)
  if ( what.length > 5)
    "#{what[0,4]}<small>#{shrink(what[5,what.length()-1])}</small>"
  else
    what
  end
end

there is a better way to write the recursive call for certain, but i don't know it right know.

moritz
+1  A: 

moritz's answer seems fine, dry-code attempt at iterative version:

def shrink(what,chunk=5)
  result = ''
  0.step(what.length, chunk) do |i|
    if i<what.length
      result << '<small>' if i>0
      result << what[i,chunk]
    end
  end
  result << '</small>'*(what.length/chunk)
  result
end
fd
seems 'shrink' fits pretty well :-)
moritz
hm. your implementation doesn't leave the first characters unshrinked. minor issue.
moritz
Are you sure? That's the intention of the post-fix "if i>0"
fd
Thank you very much to you both, moritz and fd!
Victor P