views:

1084

answers:

2

I'm trying to verify that a parameter is an instance of a specific class in Rails:

def schedule(action, *args)
  if arg.is_a? Aircraft
    ...
  end
end

I'm doing this in a library class (the file is in lib/) and I get an uninitialized constant Aircraft error. Aircraft is a model class, with a corresponding aircraft.rb file in app/models.

Can I use model classes and instances in a library? How?


Error context:

The error happens in RSpec tests; the code works in the browser. I tried requiring the model in the *spec.rb file, no success at the moment.

+1  A: 

This will give you access to the Aircraft model:

require File.dirname(__FILE__) + "/../app/models/aircraft"

[edit]

Daniel brings up a good point about the context. If you're using a rake task make sure you load the environment:

task :my_task => :environment do
  # something happens...
end
Mike Breen
+2  A: 

You can use model classes in Rails library files and you are doing it in exactly the correct fashion. Rails should autoload the class Aircraft when it is referred to.

So we need a bit more context to figure out why it is failing for you. Is it possible you are loading the lib/ file without the Rails environment?

One way to solve this would be to explicitly require the model file aircraft.rb. However, you will find this approach quickly leads to insanity as it will break the Rails auto-loader in subtle and astonishing ways. Rails is much easier if you work with the Rails class loader, not against it.

Update

So if it's in an RSpec test, can we see the code you're using to load the environment in the spec file? It should look something like this:

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

and it needs to be at the top of the file. This is assuming both that you have the RSpec Rails plugin installed (here) and that you have the default spec/spec_helper.rb file from the RSpec plugin. If there is no such file, try running:

ruby script/generate rspec
Daniel Lucraft
Ah, thank you very much! You pointed me in the right direction: it works perfectly well in the browser. I didn't try it yet because I'm doing TDD: it breaks in RSpec. I'll amend the question.
Christian Lescuyer