[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Re: Advice on using define_method in ActiveRecord descendant

Gavin Kistner

9/22/2006 10:17:00 PM

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

1 Answer

Wes Gamble

9/25/2006 3:15:00 PM

0

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