Search code examples
rubymodeldatamapperobserver-pattern

How do I separate datamapper observer class into a different file from the model class?


I'm running into an error when I try to split the dm-observer class into a separate file from my model class. Previously it worked fine if I put it all into a single file.

# test_observer.rb
require 'dm-observer'

class TestObserver
  include DataMapper::Observer
  observe Test 

  before :create do
      # does funky stuff
  end 
end 

# test.rb  
require 'dm-core'
require File.dirname(__FILE__) + '/test_observer'

class Test
  include DataMapper::Resource

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

Every time I require the Test class, I run into the error:

uninitialized constant TestObserver::Test (NameError)

I'm not sure why the TestObserver:: is prepended to the class name. I have a feeling I'm not putting the requires in the right places, but I've tried everything and it still won't play nice. Would appreciate any help on this.

Thanks!


Solution

  • You require test.rb which requires test_observer before Test class is declared. You should remove this line:

    require File.dirname(__FILE__) + '/test_observer'

    and require files in that order:

    require 'test'

    require 'test_observer'