As an organizer of a meetup on Flatiron School‘s campus, I meet some interesting people and we do some silly things that are inspired by our founder Avi Flombaum.
Now, one thing that’s really awesome to experiment with in Ruby is meta-programming. Meta-programming is writing code that writes code for you and one of the best examples of that is writing a method that accepts a hash as an argument and assigns values to attributes based on what’s passed in.
This is called `mass assignment` and looks something like this:
If you initialize the user with a hash, it will assign a variable for each key in the hash and then set the value of that variable to the value of corresponding key.
It’s pretty cool. But tonight, we began talking about metaprogramming and I pulled up some code that had been in my github for a long time, waiting to be refactored(so it actually works).
Here’s what I found:
Sweet. I was attempting it, but it didn’t actually work. So tonight we got a bit silly and actually implemented something that worked. The key to this was using `Object.get_const(model_name)` and that made all of the difference.
Here’s a basic version that would need some tweaking to truly work for all controllers.
Since this is so basic, we’d need to account for various controllers with unique pluralizations.
Thankfully, Rails provides the method `singularize`!
There we have it! Something that we should probably never, ever use. But sometimes it feels good to write code because we can.
Leave a Reply