sup

A curses threads-with-tags style email client

sup.git

git clone https://supmua.dev/git/sup/
commit 6b24e17f519db65727f967f49e6ec7b146c88e50
parent 1728fa29d1fcad67ae4353d825becff039a8dff9
Author: Whyme Lyu <callme5long@gmail.com>
Date:   Sun, 26 May 2013 16:56:28 +0800

Implement String#display_length w/ unicode library

Diffstat:
M lib/sup/util.rb | 10 ++--------
M sup.gemspec | 1 +
A test/unit/util/string.rb | 23 +++++++++++++++++++++++
3 files changed, 26 insertions(+), 8 deletions(-)
diff --git a/lib/sup/util.rb b/lib/sup/util.rb
@@ -7,6 +7,7 @@ require 'pathname'
 require 'set'
 require 'enumerator'
 require 'benchmark'
+require 'unicode'
 
 ## time for some monkeypatching!
 class Symbol
@@ -254,15 +255,8 @@ class Object
 end
 
 class String
-  ## nasty multibyte hack for ruby 1.8. if it's utf-8, split into chars using
-  ## the utf8 regex and count those. otherwise, use the byte length.
   def display_length
-    if RUBY_VERSION < '1.9.1' && ($encoding == "UTF-8" || $encoding == "utf8")
-      # scan hack is somewhat slow, worth trying to cache
-      @display_length ||= scan(/./u).size
-    else
-      size
-    end
+    @display_length ||= Unicode.width(self, false)
   end
 
   def camel_to_hyphy
diff --git a/sup.gemspec b/sup.gemspec
@@ -52,6 +52,7 @@ SUP: Please run `sup-psych-ify-config-files` to migrate from 0.13 to 0.14
     s.add_runtime_dependency "mime-types", "~> 1.0"
     s.add_runtime_dependency "locale", "~> 2.0"
     s.add_runtime_dependency "chronic", "~> 0.9.1"
+    s.add_runtime_dependency "unicode", "~> 0.4.4"
 
     s.add_development_dependency "bundler", "~> 1.3"
     s.add_development_dependency "rake"
diff --git a/test/unit/util/string.rb b/test/unit/util/string.rb
@@ -0,0 +1,23 @@
+# encoding: utf-8
+
+require "test_helper"
+
+require "sup/util"
+
+describe "Sup's String extension" do
+  describe "#display_length" do
+    let :data do
+      [
+        ['some words', 10,],
+        ['中文', 4,],
+        ['ä', 1,],
+      ]
+    end
+
+    it "calculates display length of a string" do
+      data.each do |(str, length)|
+        str.display_length.must_equal length
+      end
+    end
+  end
+end