Re: Advice on using define_method in ActiveRecord descendant

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(/,/, ‘’))

You’re not defining the method quite correctly. You want the new_value
param to be an argument to the block.

class Foo
[:bar, :jim, :jam].each{ |method_name|
define_method( “#{method_name}=”){ |new_value|
puts "The new value for ‘#{method_name}’ is " + new_value.to_s

f = = 42
#=> The new value for ‘bar’ is 42

Also, there’s no reason to use #to_s inside string interpolation; it
happens automatically.


Thanks - worked like a charm. Unfort. there aren’t any readily
available examples of define_method where parameters are used. Makes
sense to me that these would be block parameters now though.

Again, thanks.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs