Hi --

On Sat, 17 Oct 2009, Bill Devaul wrote:

>
> I've clearly go a lot of repetition in the following methods:
>
>  def name=(value)
>    write_attribute(:name, if [0,"0",""," "].include? value then nil
> else value end)
>  end
>  def address=(value)
>    write_attribute(:address, if [0,"0",""," "].include? value then nil
> else value end)
>  end
>  def city=(value)
>    write_attribute(:city, if [0,"0",""," "].include? value then nil
> else value end)
>  end
>
> Can someone tell me the convention to DRY this code?  I'm wondering if I
> use a lambda but am not quite sure that's the right path or how to do
> that.

One idea is simply to parameterize the process:

   def generic_writer(attr, value)
     @blanks ||= [0, "0", "", " "]
     write_attribute(attr, @blanks.include?(value) ? nil : value)
   end

   def name=(value)
     generic_writer(:name, value)
   end

etc.

If you want, you can automate the creation of the methods instead:

   %w{ name address city }.each do |attr|
     define_method("#{attr}=") do |value|
       @blanks ||= [0, "0", "", " "]
       write_attribute(attr, @blanks.include?(value) ? nil : value)
     end
   end


David

-- 
The          Ruby training with D. Black, G. Brown, J.McAnally
Compleat     Jan 22-23, 2010, Tampa, FL
Rubyist      http://www.thecompleatrubyist.com

David A. Black/Ruby Power and Light, LLC (http://www.rubypal.com)

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to 
[email protected]
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to