Class: Analects::CedictLoader
- Inherits:
-
Object
- Object
- Analects::CedictLoader
- Includes:
- Enumerable
- Defined in:
- lib/analects/cedict_loader.rb
Instance Attribute Summary collapse
-
#headers ⇒ Object
readonly
Returns the value of attribute headers.
Instance Method Summary collapse
- #each(&blk) ⇒ Object
- #field_names ⇒ Object
- #find_by(qry) ⇒ Object
-
#initialize(io, library) ⇒ CedictLoader
constructor
A new instance of CedictLoader.
- #lookup_index(field) ⇒ Object
Constructor Details
#initialize(io, library) ⇒ CedictLoader
Returns a new instance of CedictLoader.
9 10 11 12 13 14 15 16 17 18 |
# File 'lib/analects/cedict_loader.rb', line 9 def initialize(io, library) @contents = io.read @headers = {} @contents.each_line do |line| if line =~ /^#! (.*)=(.*)/ @headers[$1.strip] = $2.strip end break unless line =~ /^#/ end end |
Instance Attribute Details
#headers ⇒ Object (readonly)
Returns the value of attribute headers.
7 8 9 |
# File 'lib/analects/cedict_loader.rb', line 7 def headers @headers end |
Instance Method Details
#each(&blk) ⇒ Object
24 25 26 27 28 29 30 |
# File 'lib/analects/cedict_loader.rb', line 24 def each(&blk) return to_enum(__method__) unless block_given? @entries ||= @contents.each_line.map do |line| process_contents(line) if line !~ /^#/ end.compact @entries.each(&blk) end |
#field_names ⇒ Object
20 21 22 |
# File 'lib/analects/cedict_loader.rb', line 20 def field_names [:traditional, :simplified, :pinyin, :definitions] end |
#find_by(qry) ⇒ Object
32 33 34 |
# File 'lib/analects/cedict_loader.rb', line 32 def find_by(qry) qry.map {|field, value| lookup_index(field).fetch(value, [])}.inject {|r1, r2| r1 & r2} end |
#lookup_index(field) ⇒ Object
36 37 38 39 40 41 42 43 |
# File 'lib/analects/cedict_loader.rb', line 36 def lookup_index(field) @indexes ||= field_names.each_with_object({}) do |field, acc| acc[field] = each_with_object({}) do |entry, acc| (acc[entry[field_names.index(field)]] ||= []) << entry end end @indexes[field] end |