ActiveModel::AttributeMethods
What does ActiveModel::AttributeMethods do?
Basically if we include the module ActiveModel::AttributeMethods we can add the custom prefix or suffix to the methods.
For eg:-
Suppose you have a students table and it consists of column name but at some places you just need the first name from the full name? or suppose you have the requirement that you need to create three different methods to check if the data already exists? like name_taken?, email_taken? and phone_taken?.
Creating 3 different methods just to check the existence will not be a good idea if you have module like ActiveModel::AttributeMethods.
Let’s look into the code
require 'active_model'
class Student
include ActiveModel::API
include ActiveModel::AttributeMethods attribute_method_prefix 'first_'
attribute_method_prefix 'last_'
define_attribute_methods 'name' attr_accessor :name
# this will create a method 'first_name'
def first_attribute(attribute)
send(attribute).split.first
end # This will create a method last_name
def last_attribute(attribute)
send(attribute).split.last
end
endstudent = Student.new(name: 'pratik vyas')
p student.first_name #=> "pratik"
p student.last_name #=> "vyas"
In the Above class we have included two modules from the ActiveModel
If you’re not familiar with ActiveModel::API, Please checkout what is activemodel:api?
so basically what these 3 lines:
attribute_method_prefix 'first_'
attribute_method_prefix 'last_'
define_attribute_methods 'name'
does is, they gave us prefix to put for the methods first_attribute and last_attribute.
And attribute will be replaced by the argument passed in define_attribute_methods. In our case it is name.
Thanks for giving it a read!
Happy coding ;)