Skip to content

Instantly share code, notes, and snippets.

@mollerhoj
Created February 17, 2019 15:52
Show Gist options
  • Save mollerhoj/789af5f206fed25acce948e0a7a94b2d to your computer and use it in GitHub Desktop.
Save mollerhoj/789af5f206fed25acce948e0a7a94b2d to your computer and use it in GitHub Desktop.
script to translate rails projects
require 'colorize'
PATTERNS = {
rb: {
quotes: /(?<free-quote>['"][A-Z].+?['"])/
},
html_erb: {
tag_content_start: />(?<tag-content>(?!&.*;)[[:space:][:alnum:][:punct:]]+?)<%/,
button_to: /<%=\s*button_to\s+(?!.*&.*;)(?<title>['"].+?['"])/,
link_to: /<%=\s*link_to\s+(?!.*&.*;)(?<title>['"].+?['"])/,
label_tag1: /<%=.*label(_tag)?[^,]+?(?<label-title>(['"].+?['"]|:[[:alnum:]_]+))[^,]+%>.*$/,
label_tag2: /<%=.*label(_tag)?.*?,\s*(?<label-title>(['"].+?['"]|:[[:alnum:]_]+))/,
submit_tag: /<%=.*submit(_tag)?\s+(?<submit-text>(['"].+?['"]|:[[:alnum:]_]+))/,
tag_content: />(?<tag-content>(?!&.*;)[[:space:][:alnum:][:punct:]]+?)<\//
}
}
# Find all files
paths = Dir.glob("**/*.html.erb") + Dir.glob("**/*_controller.rb")
paths.each do |path|
puts path.green
puts ("-" * path.size).green
text = File.read(File.expand_path(path)).force_encoding("UTF-8")
new_text = text.split("\n").map do |line|
new_line = nil
if path.end_with?('.html.erb')
p = :html_erb
else
p = :rb
end
PATTERNS[p].each do |key, pattern|
if m = pattern.match(line)
m.names.each do |group_name|
if /\w/.match(m[group_name])
if group_name == 'tag-content'
new_line = line.gsub(m[group_name], "<%= _('#{m[group_name]}' %>')")
new_line_color = line.gsub(m[group_name], "<%= _('#{m[group_name]}') %>".blue)
else
new_line = line.gsub(m[group_name], "_(#{m[group_name]})")
new_line_color = line.gsub(m[group_name], "_(#{m[group_name]})".blue)
end
puts key.to_s.yellow
puts line.gsub(m[group_name], m[group_name].red)
puts new_line_color
end
end
end
end
unless new_line
puts line
end
new_line || line
end.join("\n") + "\n"
dry_run = false
unless dry_run
open(File.expand_path(path), "w") { |f| f.write(new_text) }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment