class Strings::Inflection::Parser

Public Class Methods

new(str, count) click to toggle source
# File lib/strings/inflection/parser.rb, line 18
def initialize(str, count)
  @scanner = StringScanner.new(str)
  @count = count
  @value = []
end
parse(str, count) click to toggle source

Parse a string by evaluating content inside tags

@api private

# File lib/strings/inflection/parser.rb, line 13
def self.parse(str, count)
  parser = new(str, count)
  parser.parse
end

Public Instance Methods

parse() click to toggle source
# File lib/strings/inflection/parser.rb, line 24
def parse
  while !@scanner.eos?
    parse_noun || parse_verb ||
    parse_count || parse_char
  end

  @value.join
end

Private Instance Methods

fuzzy_count(count) click to toggle source

@api private

# File lib/strings/inflection/parser.rb, line 88
def fuzzy_count(count)
  if count >= 10 then "many"
  elsif count >= 6 then "several"
  elsif count >= 3 then "a few"
  elsif count == 2 then "a couple of"
  elsif count == 1 then "one"
  else "no"
  end
end
parse_char() click to toggle source

@api private

# File lib/strings/inflection/parser.rb, line 83
def parse_char
  @value << @scanner.getch
end
parse_count() click to toggle source

@api private

# File lib/strings/inflection/parser.rb, line 66
def parse_count
  if @scanner.scan(/\{\{#([^\}]*?):([^\}]+?)\}\}/)
    option = @scanner[1].to_s.tr(" ", "").downcase
    if option =~ /[^f]/
      raise "Unknown option '#{option}' in {{#:...}} tag"
    end
    amount = case option
             when "f"
               fuzzy_count(@count)
             else
               @count
             end
    @value << amount
  end
end
parse_noun() click to toggle source

@api private

# File lib/strings/inflection/parser.rb, line 36
def parse_noun
  if @scanner.scan(/\{\{N([^\}]*?):([^\}]+?)\}\}/)
    option = @scanner[1].to_s.tr(" ", "").downcase
    if option =~ /[^sp]/i
      raise "Unknown option '#{option}' in {{N:...}} tag"
    end
    inflection = if option.empty?
                   @count == 1 ? :singular : :plural
                 else
                   option == "s" ? :singular : :plural
                 end
    noun = Noun[@scanner[2].to_s.tr(" ", "")]
    @value << noun.public_send(inflection)
  end
end
parse_verb() click to toggle source

@api private

# File lib/strings/inflection/parser.rb, line 53
def parse_verb
  if @scanner.scan(/\{\{V([^\}]*?):([^\}]+?)\}\}/)
    option = @scanner[1].to_s.tr(" ", "").downcase
    if !option.empty?
      raise "Unknown option '#{option}' in {{V:...}} tag"
    end
    inflection = @count == 1 ? :singular : :plural
    verb = Verb[@scanner[2].to_s.tr(" ", "")]
    @value << verb.public_send(inflection)
  end
end