1

I have a very simple set up where I make an API call, which calls a function, which will initialize an instance of a class. Weirdly, it works the first time, but any additional attempts to refresh the page gives me an uninitialized constant error for the very class being initialized. Here's an example

Rails 3.1 Ruby 2.0

in app/controllers/static_pages_controller.rb

class StaticPagesController < ApplicationController
  require_relative 'test.rb'  
  def about
    build_fleet()
    render text: "This worked"
  end
end

and in my app/controllers/test.rb:

class Fleet
  def initialize(side)
    @ships = []
    @passive_abilities = []
    @side = side
  end
end

def build_fleet()
 att_fleet = ::Fleet.new("att")
 def_fleet = ::Fleet.new("def")
end

I go to localhost/static_pages/about and get "This worked". Hit refresh and see "Fleet uninitialized" complete with the appropriate fleet stack.

When I check the server log I see

>Started GET "/static_pages/about" for 127.0.0.1 at 2014-04-05 15:52:39 -0700
>  Processing by StaticPagesController#about as HTML
>Completed 500 Internal Server Error in 4ms
>
>NameError (uninitialized constant Fleet):
>  app/controllers/test.rb:10:in `build_fleet'
>  app/controllers/static_pages_controller.rb:4:in `about'

What's going wrong on the reload?

lurker
  • 56,987
  • 9
  • 69
  • 103
JTG
  • 8,587
  • 6
  • 31
  • 38

1 Answers1

2

This seems related to how rails in development mode tries to automatically reload code on each request.

Try the advice in this answer and replace the call to require_relative with require_or_load "./test.rb"

*Edit: * I think what's happening is that at the end of every request in development mode, rails undefines most constants it knows about. (Classes are constants.)

The next request comes in and you ask ruby to load the file. But since this second request is part of the same process, ruby remembers that it already loaded test.rb and so it is skipped.

However, it looks like Fleet is a model (even if not a database-backed model). I'd drop it in the app/models/fleet.rb and rails will auto load it just fine.

Community
  • 1
  • 1
akatakritos
  • 9,836
  • 1
  • 23
  • 29