Sha256: d92f17b624b9334bf43d88af0aa4e30064f105225bcf0fbedd49dee7ba7ec4fd

Contents?: true

Size: 1.7 KB

Versions: 1

Compression:

Stored size: 1.7 KB

Contents

module I18nSpec
  class LocaleFile
    PLURALIZATION_KEYS = %w{zero one two few many other}

    attr_accessor :filepath

    def initialize(filepath)
      @filepath = filepath
    end

    def content
      @content ||= IO.read(@filepath)
    end

    def translations
      @translations ||= Psych.load(content)
    end

    def flattened_translations
      @flattened_translations ||= flatten_tree(translations.values.first)
    end

    def pluralizations
      flatten_tree(translations).select do |key, value|
        value.is_a?(Hash)
      end
    end

    def invalid_pluralization_keys
      invalid = []
      pluralizations.each do |parent, pluralization|
        pluralization.keys.select do |key, value|
          invalid << [parent, key].join('.') unless PLURALIZATION_KEYS.include?(key)
        end
      end
      invalid
    end

    def is_parseable?
      begin
        Psych.load_file(@filepath)
        true
      rescue Psych::SyntaxError => e
        false
      end
    end

    def has_one_top_level_namespace?
      translations.keys.size == 1
    end

    def is_named_like_top_level_namespace?
      translations.keys.first == File.basename(@filepath, File.extname(@filepath))
    end

  protected

    def flatten_tree(data, prefix = '', result = {})
      data.each do |key, value|
        current_prefix = prefix.empty? ? key.to_s : "#{prefix}.#{key}"
        if !value.is_a?(Hash) || pluralization_data?(value)
          result[current_prefix] = value
        else
          flatten_tree(value, current_prefix, result)
        end
      end
      result
    end

    def pluralization_data?(data)
      keys = data.keys.map(&:to_s)
      keys.any? {|k| PLURALIZATION_KEYS.include?(k) }
    end

  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
i18n-spec-0.0.10 lib/i18n-spec/models/locale_file.rb