diff --git a/examples/character-or-string-width.rb b/examples/string_width.rb similarity index 65% rename from examples/character-or-string-width.rb rename to examples/string_width.rb index de60c358..b08e0fa1 100644 --- a/examples/character-or-string-width.rb +++ b/examples/string_width.rb @@ -1,38 +1,39 @@ -require 'rubygems' -require 'ttfunk' -require 'valuable' +# frozen_string_literal: true + # Everything you never wanted to know about glyphs: # http://chanae.walon.org/pub/ttf/ttf_glyphs.htm # this code is a substantial reworking of: # https://github.com/prawnpdf/ttfunk/blob/master/examples/metrics.rb +require 'ttfunk' + class Font attr_reader :file def initialize(path_to_file) @file = TTFunk::File.open(path_to_file) end - - def width_of( string ) - string.split('').map{|char| character_width( char )}.inject{|sum, x| sum + x} + + def width_of(string) + string.split('').sum { |char| character_width(char) } end - def character_width( character ) - width_in_units = ( horizontal_metrics.for( glyph_id( character )).advance_width ) + def character_width(character) + width_in_units = horizontal_metrics.for(glyph_id(character)).advance_width width_in_units.to_f / units_per_em end def units_per_em - @u_per_em ||= file.header.units_per_em + @units_per_em ||= file.header.units_per_em end def horizontal_metrics - @hm = file.horizontal_metrics + @horizontal_metrics ||= file.horizontal_metrics end def glyph_id(character) - character_code = character.unpack("U*").first + character_code = character.unpack1('U*') file.cmap.unicode.first[character_code] end end