0

Hoping someone can point me in the right direction with this.

I want to know if there's a way to view/fetch both new and old property values with DataMapper before the update method is called and compare the values.

The scenario is as follows: I have a ticket resource and I need to notify various interested parties about changes made to the ticket. Email notification when the payment status changes, SMS notification when the ticket get's assigned to a support staff etc.

Currently, inside my Ticket class, I have set up a callback/filter like this:

before :update, :notify_changes

def notify_changes
    ticket = Ticket.get(self.id) # Get the original
    if ticket.status != self.status
        # Send out the email notification
    end
    if ticket.assigned_support != self.assigned_support
        # Send out the SMS notification
    end
    # ... etc
end

Is there a better or more efficient way to do this without hitting the database again at ticket = Ticket.get(self.id)?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
ghstcode
  • 2,902
  • 1
  • 20
  • 30
  • Do you dislike the before update callback? Or the `if ticket.status != self.status`? – AdamT Oct 13 '13 at 01:01
  • I was hoping to find a way to do this without hitting the database again at `ticket = Ticket.get(self.id)`. If the object knows it's been changed, then hopefully it would know what has changed, right? @AdamT – ghstcode Oct 13 '13 at 08:07

2 Answers2

1

Ok, I've figured this out myself. Here it is for reference if anyone else finds themselves asking the same question:

before :update, :notify_changes

def notify_changes
    # The status property has been changed
    if !dirty_attributes[Ticket.properties[:status]].nil?
       # old status: original_attributes[Ticket.properties[:status]]
    end        

    # The assigned_support property has been changed
    if !dirty_attributes[Ticket.properties[:assigned_support]].nil?
       # old status: original_attributes[Ticket.properties[:assigned_support]]
    end        
end

Inspiration Reference: This thread

ghstcode
  • 2,902
  • 1
  • 20
  • 30
1

Yes, I was referring to dirty when I asked that. Just to add a little more incase someone else comes across this question.

There are a few methods one can call to check the status of an attribute or model object.

- (Boolean) attribute_dirty?(name)
- (Boolean) clean?
- (Boolean) dirty?
- (Hash) dirty_attributes # your choice
- (Hash) original_attributes

These are part of DataMapper::Resource and can be found here: http://rubydoc.info/github/datamapper/dm-core/master/DataMapper/Resource

AdamT
  • 6,405
  • 10
  • 49
  • 75