1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-02 22:58:01 +00:00

Add Convert A Symbol To A Constant as a rails til

This commit is contained in:
jbranchaud
2017-01-20 13:46:09 -06:00
parent fabdcd92a0
commit 2f054115c9
2 changed files with 25 additions and 1 deletions

View File

@@ -7,7 +7,7 @@ variety of languages and technologies. These are things that don't really
warrant a full blog post. These are mostly things I learn by pairing with
smart people at [Hashrocket](http://hashrocket.com/).
_495 TILs and counting..._
_496 TILs and counting..._
---
@@ -313,6 +313,7 @@ _495 TILs and counting..._
- [Capybara Page Status Code](rails/capybara-page-status-code.md)
- [Code Statistics For An Application](rails/code-statistics-for-an-application.md)
- [Conditional Class Selectors in Haml](rails/conditional-class-selectors-in-haml.md)
- [Convert A Symbol To A Constant](rails/convert-a-symbol-to-a-constant.md)
- [Creating Records of Has_One Associations](rails/creating-records-of-has-one-associations.md)
- [Custom Validation Message](rails/custom-validation-message.md)
- [Demodulize A Class Name](rails/demodulize-a-class-name.md)

View File

@@ -0,0 +1,23 @@
# Convert A Symbol To A Constant
If you have a symbol and need to convert it to a constant, perhaps because
of some metaprogramming induced by a polymorphic solution, then you may
start off on an approach like the following. In fact, I've seen a number of
StackOverflow solutions like this.
```ruby
:module.to_s.capitalize.constantize
#=> Module
```
That is great for one-word constant names, but what about multi-word
constants like `OpenStruct`. This approach will not work for the symbol
`:open_struct`. We need a more general solution.
The key is to ditch `#capitalize and instead use another ActiveSupport
method, `#classify`.
```ruby
:open_struct.to_s.classify.constantize
#=> OpenStruct
```