Question

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)?

Was it helpful?

Solution

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

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top