Requiring gem in Rails 3 Controller failing with “

2019-07-17 04:32发布

问题:

I've seen this asked a few times in other threads, but none of the answers seem to apply.

Environment: Rails 3 amazon/ecs gem from jugend. The lone file is here: http://github.com/jugend/amazon-ecs/blob/master/lib/amazon/ecs.rb

my gemfile has: gem 'amazon-ecs', :git => 'git://github.com/jugend/amazon-ecs.git'

Everything works in irb. I can run: bundle console require 'amazon/ecs' and then go to town

when I try to use it from the controller though, like so: require 'amazon/ecs'

require 'amazon/ecs'

class SearchController < ApplicationController
  def index    
  end

  def results
    Amazon::Ecs.configure do |options|
        options[:aWS_access_key_id] = '[key]'
        options[:aWS_secret_key] = '[secret]'
    end

    res = Amazon::Ecs.item_search(params[:search], {:response_group => 'Medium', :search_index => 'All'})
  end
end

I get: uninitialized constant SearchController::Amazon at line 8, where I first try to use Amazon.

the ecs.rb has a module Amazon containing a class Ecs. I'm not sure why this is working in erb, and not in rails.

I'm still kinda new to Rails, so please answer using small words. :-/

回答1:

Was given the answer. I moved my initialization code to an initializer in config/initializers file, removed the require entirely, and things worked. I don't know why though, so if someone could answer that, that'd be great.



回答2:

All of the gems require their files by default, so usually you don't need to explicitly require any files.

Speaking about your problem, it could somehow be, that your controller is run before Amazon module is processed.