I recently started making a flashcard application for language learning. It’s in the very early stages, so right now I’m just using it to practice my Chinese characters. The Word model has three significant fields:
English, so I know the definition (US input)
Chinese, so I recognize the character (Zhuyin or Pinyin input)
Pinyin, so I know the pronunciation and tones (US input)
Now, the annoying thing about that is that I can’t type Pinyin in Pinyin—the word is automatically replaced. So I’m stuck typing the alt key plenty of times and doing all kinds of pinky acrobatics to reach the falling accent (on a Chinese keyboard, the falling accent is on the tilde key).
I decided that it would be a lot quicker to simply adapt the ghetto technique, which is to type vowel1, vowel2, vowel3, vowel4 to indicate the tones. So, for example, hǎo becomes ha3o. This is very quick and easy to type. The only problem is that it’s ugly to read, and poor readability is no good when trying to learn a language.
The easy way around this is with a simple before_filter in the Word model. It looks something like this:
class Word < ActiveRecord::Base
before_save :replace_pinyin
@@replacements = {
'a1' => 'ā',
'e1' => 'ē',
'i1' => 'ī',
'o1' => 'ō',
'u1' => 'ū',
'a2' => 'á',
'e2' => 'é',
'i2' => 'í',
'o2' => 'ó',
'u2' => 'ú',
'a3' => 'ǎ',
'e3' => 'ě',
'i3' => 'ǐ',
'o3' => 'ǒ',
'u3' => 'ǔ',
'a4' => 'à',
'e4' => 'è',
'i4' => 'ì',
'o4' => 'ò',
'u4' => 'ù',
}
def replace_pinyin
@@replacements.each do |key, value|
self.pinyin.gsub!(key, value)
end
end
end
Now, before the record is saved, each ugly vowel in the Pinyin field will be replaced by the more readable version. And that’s it!