Skip to content

Instantly share code, notes, and snippets.

@kattrali
Created September 18, 2012 09:14
Show Gist options
  • Save kattrali/3742196 to your computer and use it in GitHub Desktop.
Save kattrali/3742196 to your computer and use it in GitHub Desktop.
Fun with RubyMotion! An extension of the Ruby String class to support transliteration using CFStringTransform()
# encoding: UTF-8
class String
# Extend string to include transliterations to different orthographies
# from Latin character set or the reverse (`to_latin`)
#
# Supported Orthographies:
# Arabic, Cyrillic, Greek, Hangul, Hiragana, Katakana, Latin, Thai
#
# Examples:
# assert_equals "γειά σου", "geiá sou".to_greek
# assert_equals "ひらがな", "hiragana".to_hiragana
# assert_equals "привет", "privet".to_cyrillic
#
# assert_equals "privet", "привет".to_latin
# assert_equals "privet", "privet".to_cyrillic.to_latin
def method_missing meth, *args
if meth =~ /^to_(\w+)$/
if meth.to_s == "to_latin"
transform(KCFStringTransformToLatin)
else
type = Object.const_get("KCFStringTransformLatin#{$1.capitalize}")
transform(type)
end
end
end
private
# Transform Strings by the power of Core Foundation!
# Returns a transformed copy of self, or nil if the
# transformation failed
def transform type, reverse=false
# clone the string first, since CFStringTransform does an
# in-place transformation (and returns a boolean)
string = self.clone
if CFStringTransform(string, nil, type, reverse)
string
end
end
# initialize constants, to avoid uninitialized constant NameError
def cf_constants
[
KCFStringTransformLatinGreek,
KCFStringTransformLatinArabic,
KCFStringTransformLatinCyrillic,
KCFStringTransformLatinHangul,
KCFStringTransformLatinHiragana,
KCFStringTransformLatinKatakana,
KCFStringTransformLatinThai
]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment