diff --git a/README.md b/README.md index b023dd8..c520b2c 100644 --- a/README.md +++ b/README.md @@ -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) diff --git a/rails/convert-a-symbol-to-a-constant.md b/rails/convert-a-symbol-to-a-constant.md new file mode 100644 index 0000000..19261d1 --- /dev/null +++ b/rails/convert-a-symbol-to-a-constant.md @@ -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 +```