Sha256: f08257de533924e29f373164a3bf9b97b1cc9d03773567acdcdfac7576c0aa32

Contents?: true

Size: 1.48 KB

Versions: 4

Compression:

Stored size: 1.48 KB

Contents

# encoding: utf-8

module Corrector

  # Converts a source to string using stored prefixes, words and phrases
  class Parse < String

    # Returns the source string having been parsed.
    #
    # @example
    #     str = Parse.new "километра в час", scope: "UNITS" # => "КМ/Ч"
    #     str.source # => "километра в час"
    #
    attr_reader :source

    # Parses given string, caches and returns the result of parsing.
    #
    # @example
    #     Parse.new "километра в час", scope: "UNITS" # => "КМ/Ч"
    #
    # Params:
    # +value+:: a string to be parsed
    # +scope+:: a scope (dictionary) for translations
    #
    # Returns a converted string with a +source+ method containing the source
    # string and +scope+ containing the scope for translation.
    def initialize(value = "", scope:)
      @source, @scope = value.to_s, scope
      super phrase
    end

    private

    attr_reader :scope

    def cyrillic
      @cyrillic ||= Cyrillic.new source
    end

    def words
      @words ||= Words.new(cyrillic)
    end

    def parts
      @parts ||= words.map do |word|
        Prefix.by_scope(scope).scan(word) || word
      end
    end

    def line
      @line ||= parts.map do |part|
        Word.by_scope(scope).scan(part) || part
      end.to_s
    end

    def cache_key
      @cache ||= [scope, cyrillic]
    end

    def phrase
      Rails.cache.fetch cache_key do
        Phrase.by_scope(scope).scan(line) || line
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
corrector-0.1.0 app/services/corrector/parse.rb
corrector-0.0.3 app/services/corrector/parse.rb
corrector-0.0.2 app/services/corrector/parse.rb
corrector-0.0.1 app/services/corrector/parse.rb