views:

32

answers:

1

I am starting to have some difficulty making this more DRY:

http://gist.github.com/471225

The gist of it is this:

I have a bunch of Models, contact_email, contact_call, contact_letter, etcetera.

They essential were a way for me to instantiate instances of the Email model (think of it as a template) matched with a specific instance/record of Contact.

Because the Models they reference were different, I needed a way to have the controller reference the right Model.

But this is getting complicated. I played with different ways of using 'send' and parts of Ruby to identify the associated Class so I don't need to explicitly state it, but not having luck.

Thus -- very undry...help!

A: 

well, here is my first whack at it:

def show_contact_status(contact, method, contact_class)
  if @contact_method = contact_class.for_contact(contact, method).first
    @contact_method.formatted_status_message
  else
    "no status"
  end
end

And then in your models, you would add a named scope:

named_scope :for_contact, lambda {|contact, method| 
  {:conditions => {:contact_id => contact.id, :email_id => method.id}}
}

and then a formatted_status_message method in your ContactEmail model:

def formatted_status_message
  "#{self.status.to_s} (#{self.date_sent.to_s(:long)}"
end

And in your other models:

def formatted_status_message
  "sent #{self.date_sent_to_s(:long)}"
end

and you would call the method for email:

show_contact_status(contact, method, ContactEmail)

I tried to move as much as possible to the model layer and leverage that, instead of metaprogramming in this case.

Geoff Lanotte
I see, let me try this....
Angela
Hi, I guess I am confused around the named_scope :for_contact -- the only condition it has is for :email_id...but each contact could have Email, Voicemail, Postcard, Letter..... do you think you could clarify that a bit for me, thanks!
Angela