Sha256: 45d9d4be93bbfa96f42c80953ef6a2f214ab3e6affb154cc23c2fe5c070e4f68

Contents?: true

Size: 1.14 KB

Versions: 1

Compression:

Stored size: 1.14 KB

Contents

module It
  # Parses the string and replaces all interpolations accordingly.
  class Parser
    attr_reader :string, :options

    INTERPOLATION_REGEXP = /%\{[^{}]+\}/.freeze

    def self.backend_options(options)
      options.with_indifferent_access.slice(:default, :locale, :scope)
    end

    def initialize(string, options)
      @string = string
      @options = options
    end

    def process
      handle_pluralization
      escape_string

      # For deep nesting, we repeat the process until we have no interpolations anymore
      while contains_interpolation?
        string.gsub!(INTERPOLATION_REGEXP) do |interpolation|
          Interpolation.call(interpolation, options)
        end
      end
      string.html_safe
    end

    private

    def contains_interpolation?
      string =~ INTERPOLATION_REGEXP
    end

    def handle_pluralization
      return if !string.is_a?(Hash) || !options.key?('count')

      @string = I18n.backend.send(:pluralize, locale, string, options['count'])
    end

    def locale
      options['locale'] || I18n.locale
    end

    def escape_string
      @string = String.new(ERB::Util.h(string))
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
it-2.0.0 lib/it/parser.rb