require 'rails/generators' module TmattCms module Generators class LocaleGenerator < Rails::Generators::Base source_root File.expand_path('../templates', __FILE__) argument :key, :type => :string argument :zh_value, :type => :string argument :en_value, :type => :string, :default => '' def generate_locale prefix_length = 45 blank_space = ' ' * (prefix_length - 2 - ("#{key}").length) p "#{key} => #{zh_value} | #{en_value == '' ? key : en_value}" if File.readlines('config/locales/views/global/en.yml').grep(/ #{key}: /).size == 0 File.open(File.join('config', 'locales', 'views', 'global', 'en.yml'), 'a+') do |f| f.puts " #{key}:#{blank_space}\"#{en_value == '' ? key : en_value}\"" end File.open(File.join('config', 'locales', 'views', 'global', 'zh.yml'), 'a+') do |f| f.puts " #{key}:#{blank_space}\"#{zh_value}\"" end else p "#{key} exists!!! Override?(y/n) [n]:" is_override = STDIN.gets.chomp is_override = is_override == 'y' ? true : false if is_override line_number_en = get_line_number('config/locales/views/global/en.yml', " #{key}: ") override_line('config/locales/views/global/en.yml', line_number_en, " #{key}:#{blank_space}\"#{en_value == '' ? key : en_value}\"") line_number_zh = get_line_number('config/locales/views/global/zh.yml', " #{key}: ") override_line('config/locales/views/global/zh.yml', line_number_zh, " #{key}:#{blank_space}\"#{zh_value}\"") end end end private def get_line_number(file, word) count = 0 File.open(file, "r") { |f| f.each_line { |line| count += 1 return count if line =~ /#{word}/ }} end def override_line(file_path, line_number, new_line) lines = File.readlines(file_path) lines[line_number - 1] = new_line << $/ File.open(file_path, 'w') { |f| f.write(lines.join) } end end end end