I learned how to use the send method, so make a note.
I had a form where I could attach up to two images, and I wanted to find out how big the post was, so I was trying to put in a log.
So I originally wrote the following code.
validate :checking_image_size_over_limit
def checking_image_size_over_limit
logging_image_size(image_first, 'first') if image_first.present?
logging_image_size(image_second, 'second') if image_second.present?
end
def logging_image_size(image, number)
if image&.size >= 5 * 1024 * 1024
Rails.logger.info "[#{self.class.name}] Over 5MB of images (image_#{number})"
end
end
I wanted to determine whether it was the first or the second, so I passed a string as the second argument and expanded it in the log message. However, I received a review from my senior and rewrote it, saying, "If so, you can use send with just one argument."
validate :checking_image_size_over_limit
def checking_image_size_over_limit
logging_image_size('image_first') if image_first.present?
logging_image_size('image_second') if image_second.present?
end
def logging_image_size(image)
if send(image)&.size >= 5 * 1024 * 1024
Rails.logger.info "[#{self.class.name}] Over 5MB of images (#{image})"
end
end
Speaking of send, I only had the image of using it to dynamically switch methods, but I learned that it can also be used by invoking the character string passed as an argument as a method again.
Recommended Posts