2つ以上の情報源がある際の truncate

以下のコードをお好きな model なり helper なりに。

  def smart_truncate(str, len)
    return str.truncate(len) if str.is_a?(String)
    raise ArgumentError.new(:str) unless str.is_a?(Array)
    num = str.length - 1
    return str[0].truncate(len) if num == 0
    len -= str.last.length
    (0...num).to_a.reverse.each do |i|
      each_len = len / (i+1)
      str[i] = str[i].truncate(each_len)
      len -= str[i].length
    end
    str.join("")
  end

使い方は、省略可能な文字列のセットを配列にしたものと、最終的に納めたい文字数。例えばこんな感じだ。
smart_truncate([subject, content, author, url], 140)
最後の要素は省略されずに必ず全て表示される。

動作の結果は以下のとおり。

  describe "smart_truncate" do
    it { smart_truncate("abcde", 4).should == "a..." }
    it { smart_truncate(["abcde"], 4).should == "a..." }
    it { smart_truncate(["123456","78"], 8).should == "12345678" }
    it { smart_truncate(["123456","78"], 7).should == "12...78" }
    it { smart_truncate(["123456","789012", "3456"], 16).should == "1234567890123456" }
    it { smart_truncate(["123456","789012", "3456"], 15).should == "12345678...3456" }
    it { smart_truncate(["123456","789012", "3456"], 14).should == "12...78...3456" }
    it { smart_truncate(["123456","789012", "3456"], 13).should == "12...7...3456" }
    it { smart_truncate(["12345" ,"789012", "3456"], 13).should == "123457...3456" }
  end
Comment are closed.