我正在Ruby on Rails上开发一个应用程序而且我被卡住了。我有一个类将所有奇怪的字符映射到普通字符(即é,è - > e)。我需要这个类在两个模型中,因为我不想重复代码,我想加载它,以便模型可以使用它。知道怎么做吗?
修改 * 我上传课程 *
class UtfAnalyzer<鼬::分析::分析仪 包括Ferret ::分析
CHARACTER_MAPPINGS = {
['à','á','â','ã','ä','å','ā','ă'] => 'a',
['æ'] => 'ae',
['ď','đ'] => 'd',
['ć','č','ĉ','ċ'] => 'c',
['è','é','ê','ë','ē','ę','ě','ĕ','ė',] => 'e',
['ƒ'] => 'f',
['ĝ','ğ','ġ','ģ'] => 'g',
['ĥ','ħ'] => 'h',
['ì','ì','í','î','ï','ī','ĩ','ĭ'] => 'i',
['į','ı','ij','ĵ'] => 'j',
['ķ','ĸ'] => 'k',
['ł','ľ','ĺ','ļ','ŀ'] => 'l',
['ñ','ń','ň','ņ','ʼn','ŋ'] => 'n',
['ò','ó','ô','õ','ö','ø','ō','ő','ŏ','ŏ'] => 'o',
['œ'] => 'oek',
['ą'] => 'q',
['ŕ','ř','ŗ'] => 'r',
['ś','š','ş','ŝ','ș'] => 's',
['ť','ţ','ŧ','ț'] => 't',
['ù','ú','û','ü','ū','ů','ű','ŭ','ũ','ų'] => 'u',
['ŵ'] => 'w',
['ý','ÿ','ŷ'] => 'y',
['ž','ż','ź'] => 'z'
}
HTML_MAPPINGS = {
['à', 'á', 'À', 'Á', 'ä', 'Ä'] => 'a',
['è', 'é', 'È', 'É', 'ë', 'Ë'] => 'e',
['ì', 'í', 'Ì', 'Í', 'ï', 'Ï'] => 'i',
['ò', 'ó', 'Ò', 'Ó', 'ö', 'Ö'] => 'o',
['ù', 'ú', 'Ù', 'Ú', 'ü', 'Ü'] => 'u',
['ç', 'Ç'] => 'ç'
}
def self.token_stream(field, str)
ts = MappingFilter.new(RegExpTokenizer.new(str, /([a-zA-Z0-9ÑñàáäèéëìíïòóöùúüÀÁÈÉËÌÍÏÒÓÖÙÚÜçÇ]|(&([aeiouAEIOU](acute|grave|uml)|ccedil|Ccedil);))+/), HTML_MAPPINGS)
ts = MappingFilter.new(StandardTokenizer.new(str), CHARACTER_MAPPINGS)
ts = MappingFilter.new(ts, CHARACTER_MAPPINGS)
ts = LowerCaseFilter.new(ts)
end
端
答案 0 :(得分:0)
使用模块:
module CharConverter
def convert(c)
#your conversion logic here
end
end
然后在模型中包含模块:
class MyModel < ActiveRecord::Base
include CharConverter
end
方法转换将在MyModel实例范围内可用(如MyModel.new.convert
中所示)。为了在MyModel类范围内为您提供转换(如在MyModel.convert
中),请将include CharConverter
替换为extend CharConverter
。
您可以找到有关扩展和包含here之间差异的更多信息。