-2

I'm using Rails 4 and Sublime Text. I have a couple hundred views (templates) with plain strings of text that I need to convert to translatable keys. Example:

<p>Hello world!</p>

needs to be changed to:

<%= t '.hello_world' %>

... and a corresponding line needs to be added to my I18n YAML file like so:

helo_world: "Hello world!"

Is there a faster way to do this than manually editing the text?

seymore_strongboy
  • 934
  • 10
  • 16

1 Answers1

-2

If you're using a Mac, you can set up a simple Automator script to handle most of this for you.

Open Automator, make a new "Service", and add a "Run AppleScript" action with the following code:

on run {input}
  -- Convert any capital letters to lower case
  set lowerCaseString to do shell script "echo " & input & " | tr [:upper:] [:lower:]"
  -- Convert any non letters/numbers to underscores
  set key_name to do shell script "echo " & lowerCaseString & " | sed -e 's/[^a-zA-Z0-9]/_/g' -e 's/[0-9]/N/g'"
  -- Add the new key inside the neccesary view syntax for Rails I18n
  set new_text to "<%= t '." & key_name & "' %>"
  -- Copy the key name and original string to the clipboard (for quick pasting into your I18n YAML file)
  set the clipboard to key_name & ": \"" & input & "\""
  return new_text
end run

This will do the following:

  1. Take any selected text as input
  2. Convert it to snake case (ie create a I18n key name)
  3. Replace the selected text with the neccesary Rails code to render that text via Rails I18n.
  4. Copy the key and the original text to the clipboard for easy pasting into a YAML file.

The last step is to assign a keyboard shortcut to the service. You can do this (on a mac) by going to System Preferences -> Keyboards -> Shortcuts -> Services, selecting the new service you just created, and giving it a shortcut.

seymore_strongboy
  • 934
  • 10
  • 16