bob*_*blu 1 module ruby-on-rails
我有一个这样的模块:
module Controller
module LocaleModels
def self.included(base)
base.send :include, InstanceMethods
end
module InstanceMethods
def locale_Lexeme; constantize_model('Lexeme') end
def locale_Synthetic; constantize_model('Synthetic') end
def locale_Property; constantize_model('Property') end
private
def constantize_model(common_part)
eval(I18n.locale.capitalize + '::' + common_part).constantize
end
end
end
end
Run Code Online (Sandbox Code Playgroud)
但我一直在努力
NoMethodError (undefined method `constantize' for #<Class:0x2483b0c>)
Run Code Online (Sandbox Code Playgroud)
我想我不能在自定义模块中使用'constantize'.
但是,请你提供一些解决方法吗?
该constantize方法将字符串转换为常量(例如类或模块).但是,eval调用已经返回一个类,而不是一个字符串,所以从某种意义上说它已经完成了什么constantize.
我建议删除eval呼叫,因为constantize使用起来更安全.
def constantize_model(common_part)
(I18n.locale.capitalize + '::' + common_part).constantize
end
Run Code Online (Sandbox Code Playgroud)
这样你就可以constantize根据需要调用一个字符串.