the code
def split_description(description, first_n)
@description_first, @description_remain =
case description.count("\n")
when 0..first_n
[description, '']
else
partition_description(description, first_n)
end.map(&:to_html)
end
def partition_description(description, first_n)
return ['', description] if first_n.zero?
offset = 0
description.each_line.with_index(1) do |s,i|
offset += s.size
return [description[0,offset], description[offset..-1]] if i == first_n
end
end
I assumed to_html('') #=> '', but if it is not, then the modification is simple.
Example
So that we can see the effect to_html, we define it this way.
def to_html(description)
description.upcase
end
description =<<_
It was the best of times
it was the worst of times
it was the age of wisdom
it was the age of fools
_
split_description(description, 0)
@description_first
@description_remain
split_description(description, 1)
@description_first
@description_remain
split_description(description, 2)
@description_first
@description_remain
split_description(description, 3)
@description_first
@description_remain
split_description(description, 4)
@description_first
@description_remain
Explanation
First, it turns out that descriptionis a local variable containing a string. If so, this should be the argument of the method (along with first_n).
def split_description(description, first_n)
,
@description_first, @description_remain =
: , to_html. .
case description.count("\n")
,
when 0
[description, '']
, ['', '']; .
, 1 first_n. @description_first @description_remain .
when 1..first_n
[description, '']
when 0 when 1..first_n , :
when 0..first_n
[description, '']
, first_n . , , first_n.
else
partition_description(description, first_n)
partition_description description first_n - , .
, case, , to_html,
end.map(&:to_html)
end
, to_html('') #=> ''. , .
, , , , .