I Learned About Mass Assignment

As programmers, just about the first thing we learn to do is usually assigning data to a variable. Depending on the project, the number of variables and values we need can quickly grow. When we create objects and classes that reflect real objects, those objects then have numerous attributes that we need. Now if we needed to initialize all of these attributes when instantiating objects, easily it can get tiring.

With Ruby, this process can be easier with meta programming and mass assignment. Instead of passing each individual attribute to our initialization method, we can pass a hash of the attributes. Then by iterating over the hash, we can call the send method to create the assignments upon initialization. Now, the send method is an instance method of the Object class. The first argument of the send method is what you are trying to send to the object, in other words the method of the same name. The second method is what we are passing to that method. And so with the send method, we are able to do mass assignment, as it does not rely on any specific attribute name.

I had encountered the send method while looking at ORMs and I didn’t really understand what it was doing. In that method, the send method was used to call upon values from variables that were being passed as arguments. Through the send method you can to decide which method to call at the very last moment even while the code is running. By looking up what the send method did, it made me appreciate mass assignment with Ruby.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.