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(/,/, ''))
      }
    end
  end

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|
    self.class_eval{
      define_method( "#{method_name}="){ |new_value|
        puts "The new value for '#{method_name}' is " + new_value.to_s
      }
    }
   }
end

f = Foo.new
f.bar = 42
#=> The new value for 'bar' is 42

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

Gavin,

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.
Wes

···

--
Posted via http://www.ruby-forum.com/.