inglesp
inglesp

Reputation: 3347

:symbol to Constant in rails

Is there a method in Rails that converts a symbol to a constant? I want to be able to do something like

:monkey.to_constant #=> Monkey

At the moment I have to do

:monkey.to_s.camelize.constantize

which is a bit of a mouthful.

Upvotes: 3

Views: 2999

Answers (1)

Dutow
Dutow

Reputation: 5668

class Symbol
  def to_c
    self.to_s.camelize.constantize
  end
end

:monkey.to_c

Updated for Rails >= 4

As of Rails >= 4 .classify is better to use than .camelize

# .camelize with singular and plural symbols/strings
:user.to_s.camelize.constantize
# => User
:users.to_s.camelize.constantize
# => NameError: uninitialized constant Users

# .classify with singular and plural symbols/strings
:user.to_s.classify.constantize
# => User
:users.to_s.classify.constantize
# => User

Upvotes: 6

Related Questions