Ruby字符串到类名 [英] Ruby String to Class Name

查看:70
本文介绍了Ruby字符串到类名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个新类,该类将从ActiveRecord::Base继承,该类需要从字符串动态生成

I am trying to create a new class to that will inherit from ActiveRecord::Base the class needs to be dynamically generated from a string

"general_systems".camelize.singularize = Class.new < ActiveRecord::Base

但是我仍然收到错误消息:

However I keep getting the error:

undefined method `singularize=' for "GeneralSystems":String

我还尝试了constantize字符串

>> foo = "general_systems".camelize.singularize
=> "GeneralSystem"
>> foo.constantize
NameError: uninitialized constant GeneralSystem
    from /var/lib/gems/1.9.1/gems/activesupport-3.0.5/lib/active_support/inflector/methods.rb:124:in `block in constantize'
    from /var/lib/gems/1.9.1/gems/activesupport-3.0.5/lib/active_support/inflector/methods.rb:123:in `each'
    from /var/lib/gems/1.9.1/gems/activesupport-3.0.5/lib/active_support/inflector/methods.rb:123:in `constantize'
    from /var/lib/gems/1.9.1/gems/activesupport-3.0.5/lib/active_support/core_ext/string/inflections.rb:43:in `constantize'
    from (irb):4
    from /usr/bin/irb:12:in `<main>'
>> foo.constantize = Class.new
NoMethodError: undefined method `constantize=' for "GeneralSystem":String
    from (irb):5
    from /usr/bin/irb:12:in `<main>'

任何帮助将不胜感激.

推荐答案

如果您使用的是Rails,它提供了一种称为#constantize的方法,该方法将起作用:

If you're using Rails, it provides a method called #constantize that will work:

irb(main):017:0> Object.const_get 'House::Owns'
NameError: wrong constant name House::Owns

'House::Owns'.constantize
=> House::Owns

这篇关于Ruby字符串到类名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆