From b533e8e4e2144ead0142a3eebcc4005659f17e38 Mon Sep 17 00:00:00 2001 From: baxter2 Date: Tue, 4 Jun 2019 15:55:50 +1000 Subject: [PATCH 1/2] Move setting color logic from convert_hash into initialization. --- lib/identicon.rb | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/lib/identicon.rb b/lib/identicon.rb index 4ccc22a..5c1486b 100644 --- a/lib/identicon.rb +++ b/lib/identicon.rb @@ -84,7 +84,7 @@ def blob_for(data, size = 420, background = nil) def initialize(data, size) @hash = Digest::MD5.hexdigest(data.to_s) @chars = @hash.scan(CHARS_REGEX) - @color = [0, 0, 0] + @color = COLORS[@hash.chars[11].to_sym] @size = size @pixel_ratio = (size / 6).round @image_size = @size - (@pixel_ratio / 1.5).round @@ -174,9 +174,6 @@ def convert_hash @square_array[i / 3][2] = h_to_b char end end - color = :a - 0.upto(5) { color = chars.shift.to_sym } - @color = COLORS[color] end def h_to_b(value) From 83057c69042ef1df9ced49b9ef99e70f692f39f3 Mon Sep 17 00:00:00 2001 From: baxter2 Date: Tue, 4 Jun 2019 16:21:10 +1000 Subject: [PATCH 2/2] Refactor convert_hash by transfering logic into other methods. --- lib/identicon.rb | 33 ++++++++++++++++----------------- 1 file changed, 16 insertions(+), 17 deletions(-) diff --git a/lib/identicon.rb b/lib/identicon.rb index 5c1486b..d3867b4 100644 --- a/lib/identicon.rb +++ b/lib/identicon.rb @@ -88,7 +88,7 @@ def initialize(data, size) @size = size @pixel_ratio = (size / 6).round @image_size = @size - (@pixel_ratio / 1.5).round - @square_array = Hash.new { Hash.new(false) } + @square_array = Hash.new { |h, k| h[k] = Array.new(5, false) } @background = [240, 240, 240] convert_hash end @@ -159,24 +159,23 @@ def to_blob private def convert_hash - chars = @chars.map { |p| p[1] } - chars.each_index do |i| - char = chars[i] - sq_index = (i / 3).round - @square_array[i / 3] = [] unless @square_array.member? sq_index - if i % 3 == 0 - @square_array[i / 3][0] = h_to_b char - @square_array[i / 3][4] = h_to_b char - elsif i % 3 == 1 - @square_array[i / 3][1] = h_to_b char - @square_array[i / 3][3] = h_to_b char - else - @square_array[i / 3][2] = h_to_b char - end + outer_inner_middle_columns = @chars.map { |p| p[1].ord.even? }.each_slice(3).to_a + outer_inner_middle_columns.each_with_index do |arr, row| + paint_two_outer_columns?(arr[0] , row) + paint_two_inner_columns?(arr[1] || false, row) + paint_middle_column?( arr[2] || false, row) end end - def h_to_b(value) - value.bytes.first.even? + def paint_two_outer_columns?(boolean, row) + @square_array[row][0] = boolean && @square_array[row][4] = boolean + end + + def paint_two_inner_columns?(boolean, row) + @square_array[row][1] = boolean && @square_array[row][3] = boolean + end + + def paint_middle_column?(boolean, row) + @square_array[row][2] = boolean end end