Search code examples
rubymodeldatamapperobservers

How to access old state values within datamapper observer?


I'm using dm-observer to observe my dm models, and I need to perform some actions based on state changes within the model. I've figured out that @state is used to store the updated state value, but I have not been able to figure out how to access the old state value. In the example below I've used "old_state", but obviously that does not work.

class Adam
    include DataMapper::Resource

    property :id, Serial
    property :name, String
    property :state, Integer
end

class AdamObserver
    include DataMapper::Observer
    observe Adam

    before :update do
        if old_state == 1 && @state == 2
            #do something 
        end
    end
end 

Solution

  • You can access original values via #original_attributes hash which is indexed by property objects. So the code could look like that:

    if original_attributes[properties[:state]] == 1 && state == 2
      # do something
    end