class Sy18nc::Locale

Attributes

hash[R]
name[R]

Public Class Methods

new(file) click to toggle source
# File lib/sy18nc/locale.rb, line 14
def initialize(file)
  # locale does not exists
  unless File.exists?(File.expand_path(file))
    # extracts name from locale file name
    # ["devise", "en"]
    tname = file.match(/(([A-z]+\.)*)(yml)$/)[1].split(".")
    f = File.new(file, "w+")

    # uses fetched keys before to create a skeleton of locale
    locale_skeleton = nested_hash(tname.reverse)

    f.write(YAML.dump(locale_skeleton))
    f.close
  end

  @name = File.basename(file,".*")

  file = File.read(File.expand_path(file))
  file = replace_fixmes(file)
begin
  @hash = YAML.load(file)
rescue Exception => e
  puts "Problem with parsing #{name}, check if this is a valid YAML file http://yamllint.com/."
  puts e.message
  return
end

  # little hack
  # force double-quotes everywhere
  hash.sy18nc_append!("foo \nbar")
end

Public Instance Methods

body() click to toggle source
# File lib/sy18nc/locale.rb, line 50
def body
  hash[hash.keys.first]
end
nested_hash(keys) click to toggle source

a little helper, move to separate module

# File lib/sy18nc/locale.rb, line 8
def nested_hash(keys)
  head, *tail = keys
  return {} if head.nil?
  { head => nested_hash(tail) }
end
replace_fixmes(file) click to toggle source

little trick: fetch with the comments

# File lib/sy18nc/locale.rb, line 80
def replace_fixmes(file)
  file.gsub("\' # FIXME", " g FIXME\'")
    .gsub("\" # FIXME", " g FIXME\"")
    .gsub("# FIXME", "g FIXME")
end
restore_fixmes(file) click to toggle source

little trick: restore fixmes

# File lib/sy18nc/locale.rb, line 88
def restore_fixmes(file)
  file.gsub("\sg FIXME\"", "\" # FIXME")
    .gsub("\sg FIXME\'", "\' # FIXME")
    .gsub("g FIXME", "# FIXME")
    .gsub("\"# FIXME\"", "# FIXME")
end
save(options = {}) click to toggle source
# File lib/sy18nc/locale.rb, line 68
def save(options = {})
  filename = options.fetch(:filename, "#{@name}")
  filename = "#{filename}.yml"
  filename = "#{filename}.bak" if options[:backup]

  file = File.new(filename, "w+")
  file.write(self.to_yaml)
  file.close
end
synchronizable?() click to toggle source
# File lib/sy18nc/locale.rb, line 46
def synchronizable?
  !!hash
end
synchronize(other) click to toggle source
# File lib/sy18nc/locale.rb, line 54
def synchronize(other)
  body.sy18nc_deep_merge!(other.body)
  body.sy18nc_deep_delete_unused!(other.body)
end
to_yaml() click to toggle source
# File lib/sy18nc/locale.rb, line 59
def to_yaml
  # disable line wrap
  yaml = YAML.dump(hash, line_width: -1)

  # force double quotes in every value
  yaml.gsub!("foo \\nbar","")
  restore_fixmes(yaml)
end