I try to optimize the following Accounting model class and have two questions:
1) How can i replace the multiple attribute setters with a more elegant method?
2) Is there a better way than the if conditional in the replace_comma_with_dot method
class Accounting < ActiveRecord::Base
validates :share_ksk, :central_office, :limit_value, :fix_disagio,
presence: true, numericality: { less_than: 999.99, greater_than_or_equal_to: 0.00 },
format: { with: /\d*\.\d{0,2}$/, multiline: true, message: I18n.t('accounting.two_digits_after_decimal_point')}
def share_ksk=(number)
replace_comma_with_dot(number)
super
end
def central_office=(number)
replace_comma_with_dot(number)
super
end
def limit_value=(number)
replace_comma_with_dot(number)
super
end
def fix_disagio=(number)
replace_comma_with_dot(number)
super
end
def replace_comma_with_dot(number)
if number.is_a? String
number.sub!(",", ".")
elsif number.is_a? Float
number
else
""
end
end
end
As user Pardeep suggested i'm trying to replace my getters with define_method:
[:share_ksk=, :central_office=, :limit_value=, :fix_disagio=].each do |method_name|
self.class.send :define_method, method_name do |number|
replace_comma_with_dot(number)
super
end
end
What am i missing?