99miles
99miles

Reputation: 11212

Rails lib load order

I have the following classes in my applications lib directory:

proxy.rb

class Proxy
end

ga_proxy.rb

class GaProxy < Proxy
  include GaProxy::Metrics
end

metrics.rb

class GaProxy
  module Metrics
  end
end

Load order clearly matters here:

metrics.rb need to be loaded before ga_proxy.rb

proxy.rb needs to be loaded before ga_proxy.rb

But if metrics.rb is loaded before ga_proxy, then I get 'superclass mismatch for class GaProxy' because GaProxy has already been defined without a parent class.

How can I get around this issue?

Thanks

Upvotes: 3

Views: 2223

Answers (3)

Artem Kalinchuk
Artem Kalinchuk

Reputation: 6652

In your application.rb file, specify each file you want to load in order:

config.autoload_paths += %W( #{config.root}/lib/proxy.rb, #{config.root}/lib/metrics.rb, #{config.root}/lib/ga_proxy.rb )

Upvotes: 1

gylaz
gylaz

Reputation: 13581

Generally, in ruby, you require what you need in your file:

# ga_proxy.rb
require './proxy'
require './metrics'

class GaProxy < Proxy
  include GaProxy::Metrics
end

That's assuming the files live in the same directory. Of course, Rails does some autoloading magic for you, but you can still be explicit about your requires.

Edit

You'll have to specify the superclass in metrics.rb:

# metrics.rb
class GaProxy < Proxy
  module Metrics
  end
end

Upvotes: 0

drhenner
drhenner

Reputation: 2230

I've never had this issue but why can't you do the following in config/initializers

create a file config/initializers/libs.rb

 require 'proxy'
 require 'ga_proxy'
 require 'metrics'

Upvotes: 0

Related Questions