开发者

rails: How do I convert a symbol to a class

Given a symbol in rails, how do I get a Class? So I could call something like:

give_class(:post).find(:all)

or si开发者_开发技巧milar.


First, convert to string.

class_name = symbol.to_s

From there, you will need to format the string into a proper class name using the methods provided by ActiveSupport's Inflector.

  • camelize will turn 'my_module' into 'MyModule'
  • classify will turn 'my_models' into 'MyModel'

camelize is more likely the one you want, given your code snippet.

Then use the constantize method:

klass = class_name.constantize

Classy!


I was searching stackoverflow for this answer and couldn't find it worded how I was looking for it, so I thought I would Q&A myself:

  • :symbol to Constant in rails

The answer above was correct, but I acutally found the docs that explain a bit better:

  • http://api.rubyonrails.org/classes/ActiveSupport/CoreExtensions/String/Inflections.html#M001360

There are basically two methods:

  • .to_s.camelize - used when you have the singular form (:post)
  • .to_s.classify - used when you have a plural form (:posts)

From that, you call constantize, and Viola! you have your class.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜