Sha256: 37876d1aa6aab326d0e40766fb67f233cc4a33c8a27c81881154486922490221

Contents?: true

Size: 1.42 KB

Versions: 1

Compression:

Stored size: 1.42 KB

Contents

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

    def initialize(filepath)
      @filepath = filepath
    end

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

    def has_valid_pluralization_keys?
      pluralizations.each do |key, pluralization|
        return false unless pluralization.keys.all? {|k| PLURALIZATION_KEYS.include?(k)}
      end
      true
    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 translations
      @translations ||= Psych.load_file(@filepath)
    end

    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

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

Version data entries

1 entries across 1 versions & 1 rubygems

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