Sha256: 8adeb7fd67c5787aace2eb7cf38605ea66e28cc29cbd0ce4d0f43cbf0d6f5aa3

Contents?: true

Size: 1.59 KB

Versions: 1

Compression:

Stored size: 1.59 KB

Contents

require 'yaml'
require 'psych'

module MissingTranslation
  class TranslationFile
    attr_accessor :pathname, :content, :group, :language, :translations

    def initialize(pathname = nil)
      return unless pathname

      @pathname = pathname
      @file = File.open(pathname)
      if @file
        @content = (YAML.load(@file.read) || {})
      end
    end

    def to_json
      return nil unless @content
      
      hash_content = @content.to_hash
      return hash_content[language] if hash_content.has_key?(language)
      
      hash_content
    end

    def group
      return @group if @group

      groups = pathname.split('/').last.gsub('.yml', '').split('.')
      return '' unless groups.size > 1

      @group = groups.first
    end

    def language
      return @language if @language

      @language = pathname.split('/').last.gsub('.yml', '').split('.').last
    end

    def write(directory)
      return nil unless translations

      result = Psych.parse_stream translations.to_yaml
      result.grep(Psych::Nodes::Scalar).each do |node|
        node.plain  = false
        node.quoted = true
        node.style = Psych::Nodes::Scalar::DOUBLE_QUOTED
      end
      result.grep(Psych::Nodes::Mapping).each do |node|
        node.children.each_slice(2) do |k, _|
          k.plain  = true
          k.quoted = false
          k.style  = Psych::Nodes::Scalar::ANY
        end
      end
      filename = [group, language, "yml"].compact.reject{|s| s.size <= 0}.join('.')

      p "Writing file #{directory}/#{filename}..."
      File.write("#{directory}/#{filename}", result.yaml)
    end

  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
missing_translation-0.2.1 lib/missing_translation/translation_file.rb