Using the local_assigns Hash to Access Rails Partial Local Variables
In the DoggieDashboard blog, there's a Facebook comments partial. This partial is used in the blog views to automatically enter the correct URL slug into the comment partial, so that Facebook can correct track the comments with the correct blog post. The blog's URL is inserted into the URL slot.
Recently, I wanted to be able to change the generic H3 header inside the comment partial: "Any advice you'd like to give fellow pet businesses? If so, please leave it in the comments below." I added the custom_title local outside the partial and inside the partial, I checked to see if the custom_title local was available.
This, however, caused all my blog posts to start breaking because their partial call didn't include a "custom_title: nil" assignment. There were two choices. I could go find every time I used to comment partial and add a nil value for custom_title, or I could figure out a way to check for the existence of a local variable inside partial.
That's when I found this StackOverflow post and learned about the local_assigns method.
After learning about this local_assigns hash (that I have never heard about before), I could now check to see if there was a custom_title key inside the local_assigns hash. If there was, I'd use it to set my custom title inside the Facebook comment partial. If there wasn't a custom_title key available, I'd just use the generic one that shows up above all blog posts, etc.