Advice on using define_method in ActiveRecord descendant

W

Wes Gamble

All,

I have five accessor methods in an AR descendant that are virtually the
same. I wanted to try and use define_method to auto-define all five
methods, but I can't seem to get it to work.

Here are the methods:

def gross_receipts=(new_value)
write_attribute:)gross_receipts, new_value.to_s.gsub(/,/, ''))
end

def number_of_owners=(new_value)
write_attribute:)number_of_owners, new_value.to_s.gsub(/,/, ''))
end

def annual_employee_payroll=(new_value)
write_attribute:)annual_employee_payroll, new_value.to_s.gsub(/,/,
''))
end

def uninsured_subcontractors_contract_cost=(new_value)
write_attribute:)uninsured_subcontractors_contract_cost,
new_value.to_s.gsub(/,/, ''))
end

def insured_subcontractors_contract_cost=(new_value)
write_attribute:)insured_subcontractors_contract_cost,
new_value.to_s.gsub(/,/, ''))
end

and here is what I tried to do to auto-create them:

for attr in [ :gross_receipts, :number_of_owners,
:annual_employee_payroll, :uninsured_subcontractors_contract_cost,
:insured_subcontractors_contract_cost ] do
self.class_eval do
define_method("#{attr.to_s}=(new_value)") {
write_attribute(attr, new_value.to_s.gsub(/,/, ''))
}
end
end

The for loop is syntactically correct, but these methods do not exist if
I create a new instance of this object.

Is it because these methods don't exist in the first place (they're
auto-created by ActiveRecord anyway)?

What am I doing wrong?

Thanks,
Wes
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,213
Messages
2,571,107
Members
47,699
Latest member
lovelybaghel

Latest Threads

Top