mirror of
https://github.com/jbranchaud/til
synced 2026-01-03 07:08:01 +00:00
Add Convert A Symbol To A Constant as a rails til
This commit is contained in:
@@ -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
|
warrant a full blog post. These are mostly things I learn by pairing with
|
||||||
smart people at [Hashrocket](http://hashrocket.com/).
|
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)
|
- [Capybara Page Status Code](rails/capybara-page-status-code.md)
|
||||||
- [Code Statistics For An Application](rails/code-statistics-for-an-application.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)
|
- [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)
|
- [Creating Records of Has_One Associations](rails/creating-records-of-has-one-associations.md)
|
||||||
- [Custom Validation Message](rails/custom-validation-message.md)
|
- [Custom Validation Message](rails/custom-validation-message.md)
|
||||||
- [Demodulize A Class Name](rails/demodulize-a-class-name.md)
|
- [Demodulize A Class Name](rails/demodulize-a-class-name.md)
|
||||||
|
|||||||
23
rails/convert-a-symbol-to-a-constant.md
Normal file
23
rails/convert-a-symbol-to-a-constant.md
Normal 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
|
||||||
|
```
|
||||||
Reference in New Issue
Block a user