mirror of
https://github.com/jbranchaud/til
synced 2026-01-05 08:08:02 +00:00
Add Convert A Symbol To A Constant as a rails til
This commit is contained in:
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