开发者

rails: How do I convert a symbol to a class

开发者 https://www.devze.com 2022-12-19 01:36 出处:网络
Given a symbol in rails, how do I get a Class?So I could call something like: give_class(:post).find(:all)

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

精彩评论

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

关注公众号