Class: TextAlignment::CharMapping

Inherits:
Object
  • Object
show all
Defined in:
lib/text_alignment/char_mapping.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(_text, char_mapping = nil, to_ignore_whitespaces = false) ⇒ CharMapping

Returns a new instance of CharMapping.



85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
# File 'lib/text_alignment/char_mapping.rb', line 85

def initialize(_text, char_mapping = nil, to_ignore_whitespaces = false)
	if to_ignore_whitespaces
		@method_get_positions_squeeze_ws = method(:get_positions_squeeze_ws_0)
		@method_squeeze_ws = method(:squeeze_ws_0!)
	else
		@method_get_positions_squeeze_ws = method(:get_positions_squeeze_ws_1)
		@method_squeeze_ws = method(:squeeze_ws_1!)
	end

	@text  = _text

	# sort by the length of the spell-outs is important
	char_mapping ||= TextAlignment::CHAR_MAPPING.sort{|a, b| b[1].length <=> a[1].length}
	@mapped_text, offset_mapping = enmap_text(_text, char_mapping)
	@index_enmap = offset_mapping.to_h
	@index_demap = offset_mapping.map{|m| m.reverse}.to_h
end

Instance Attribute Details

#index_enmapObject (readonly)

Returns the value of attribute index_enmap.



83
84
85
# File 'lib/text_alignment/char_mapping.rb', line 83

def index_enmap
  @index_enmap
end

#mapped_textObject (readonly)

Returns the value of attribute mapped_text.



83
84
85
# File 'lib/text_alignment/char_mapping.rb', line 83

def mapped_text
  @mapped_text
end

Instance Method Details

#demap_position(position) ⇒ Object



107
108
109
# File 'lib/text_alignment/char_mapping.rb', line 107

def demap_position(position)
	@index_demap[position] || raise(ArgumentError, "Unusual position of annotation: #{position}")
end

#enmap_denotations(denotations) ⇒ Object



111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
# File 'lib/text_alignment/char_mapping.rb', line 111

def enmap_denotations(denotations)
	return nil if denotations.nil?

	denotations.map do |d|
		d.dup.merge(span:{begin:enmap_position(d[:span][:begin]), end:enmap_position(d[:span][:end])})
	rescue ArgumentError => e
		snippet_begin = d[:span][:begin] - 5
		if snippet_begin < 0
			snippet_begin = 0
		end
		snippet_end = d[:span][:end] + 5
		if snippet_end > @text.length
			snippet_end = @text.length
		end
		snippet = @text[snippet_begin ... d[:span][:begin]] + '[' + @text[d[:span][:begin] ... d[:span][:end]] + ']' + @text[d[:span][:end] ... snippet_end]
		if snippet_begin > 0
			snippet = '...' + snippet
		end
		if snippet_end < @text.length
			snippet = snippet + '...'
		end
		raise ArgumentError, e.message + " (#{snippet})"
	end
end

#enmap_position(position) ⇒ Object



103
104
105
# File 'lib/text_alignment/char_mapping.rb', line 103

def enmap_position(position)
	@index_enmap[position] || raise(ArgumentError, "Unusual position of annotation: #{position}")
end