]> cat aescling's git repositories - mastodon.git/commitdiff
Add tests for StreamEntriesHelper#rtl? (#2286)
authorJoël Quenneville <joel.quen@gmail.com>
Fri, 21 Apr 2017 22:13:37 +0000 (18:13 -0400)
committerEugen <eugen@zeonfederated.com>
Fri, 21 Apr 2017 22:13:37 +0000 (00:13 +0200)
We used some random Arabic characters to test that the various RTL
conditions got triggered.

app/helpers/stream_entries_helper.rb
spec/helpers/stream_entries_helper_spec.rb

index 00a01df44d60af49bc202560d48f36953e013603..daa4a48e48e938e9b1a3e121798dc33ad984d466 100644 (file)
@@ -37,20 +37,22 @@ module StreamEntriesHelper
   end
 
   def rtl?(text)
-    return false if text.empty?
+    rtl_characters = /[\p{Hebrew}|\p{Arabic}|\p{Syriac}|\p{Thaana}|\p{Nko}]+/m.match(text)
 
-    matches = /[\p{Hebrew}|\p{Arabic}|\p{Syriac}|\p{Thaana}|\p{Nko}]+/m.match(text)
-
-    return false unless matches
-
-    rtl_size = matches.to_a.reduce(0) { |acc, elem| acc + elem.size }.to_f
-    ltr_size = text.strip.size.to_f
-
-    rtl_size / ltr_size > 0.3
+    if rtl_characters.present?
+      total_size = text.strip.size.to_f
+      rtl_size(rtl_characters.to_a) / total_size > 0.3
+    else
+      false
+    end
   end
 
   private
 
+  def rtl_size(characters)
+    characters.reduce(0) { |acc, elem| acc + elem.size }.to_f
+  end
+
   def embedded_view?
     params[:controller] == 'stream_entries' && params[:action] == 'embed'
   end
index e2544e311a010b93d454844e7ab9622bd1c64c35..706a872f1ab581425e23a6603b03ebb3ce0c2dc7 100644 (file)
@@ -14,4 +14,22 @@ RSpec.describe StreamEntriesHelper, type: :helper do
       expect(helper.display_name(account)).to eq "Username"
     end
   end
+
+  describe '#rtl?' do
+    it 'is false if text is empty' do
+      expect(helper).not_to be_rtl ''
+    end
+
+    it 'is false if there are no right to left characters' do
+      expect(helper).not_to be_rtl 'hello world'
+    end
+
+    it 'is false if right to left characters are fewer than 1/3 of total text' do
+      expect(helper).not_to be_rtl 'hello ݟ world'
+    end
+
+    it 'is true if right to left characters are greater than 1/3 of total text' do
+      expect(helper).to be_rtl 'aaݟ'
+    end
+  end
 end