Posted By

67ideas on 02/07/10


Tagged

rails activerecord pinyin chinese


Versions (?)

Convert Between Simple Tone Input and Pinyin in Rails model


 / Published in: Rails
 

URL: http://67ideas.com/blog/easily-translate-rails-form-inputs-saving

This lets you type Mandarin tones like a1, o2, e3, and so on instead of having to type the real pinyin. The tones are saved with the proper characters in the database.

  1. class Word < ActiveRecord::Base
  2. before_save :replace_pinyin
  3.  
  4. @@replacements = {
  5. 'a1' => 'ā',
  6. 'e1' => 'ē',
  7. 'i1' => 'ī',
  8. 'o1' => 'ō',
  9. 'u1' => 'ū',
  10. 'a2' => 'á',
  11. 'e2' => 'é',
  12. 'i2' => 'í',
  13. 'o2' => 'ó',
  14. 'u2' => 'ú',
  15. 'a3' => 'ǎ',
  16. 'e3' => 'ě',
  17. 'i3' => 'ǐ',
  18. 'o3' => 'ǒ',
  19. 'u3' => 'ǔ',
  20. 'a4' => 'à',
  21. 'e4' => 'è',
  22. 'i4' => 'ì',
  23. 'o4' => 'ò',
  24. 'u4' => 'ù',
  25. }
  26.  
  27. def replace_pinyin
  28. @@replacements.each do |key, value|
  29. self.pinyin.gsub!(key, value)
  30. end
  31. end
  32. end

Report this snippet  

You need to login to post a comment.