I am building a rails app that i need to update totals of managers each time someone is added. The method that updates the totals to me is looking really bad there is a lot of repetition going on that could be solved with a bit of metaprogramming. so i have a private method being called on before_save
called update_totals
So we categorize them like this there is four races, african, coloured, indian and white there are three kinds of managements senior, middle and junior and then obviously two kinds of genders male and female. I need to be able to assign each possible variation of the three so i end up with something like this.
self.number_of_african_female_senior_managers = managers.native.african.female.senior.count
self.number_of_african_male_senior_managers = managers.native.african.male.senior.count
self.number_of_african_female_middle_managers = managers.native.african.female.middle.count
self.number_of_african_male_middle_managers = managers.native.african.male.middle.count
self.number_of_african_female_junior_managers = managers.native.african.female.junior.count
self.number_of_african_male_junior_managers = managers.native.african.male.junior.count
I would need to do this for each race. So i thought of building them dynamically and then having them assigned.
So something like this:
["african", "indian", "coloured", "white"].each do |race|
["senior","middle","junior"].each do |management_type|
["male","Female"].each do |gender|
"number_of_#{race}_#{gender}_#{management_type}_managers" = managers.native.race.gender.management_type.count
end
end
end
But this will return strings and not variables that be assigned. I saw there is a define_method
method that can dynamically build methods but that looks like you have to call it outside of the constructor in this example, and i saw that you can use Object#send
like this example, but i cant see that working in this situation either.
Is this a good ruby practice? Its adding a bit of complexity but removing a lot of DRY code.