Khiem Nguyen Khiem Nguyen - 4 months ago 20
Ruby Question

rake aborted! NameError: uninitialized constant even add :enviroment to task

I'm newbie to RoR and trying to create a task to import database from google spreadsheet by creating an Importer under lib/spreadsheet. but rake cannot find my importer even I added :environment to task according to some others issues in SOF. here are my files

lib/spreadsheet/importer.rb

class SpreadSheet::Importer
def initialize
@session = GoogleDrive.saved_session("#{Rails.root}/config/google_drive/config.json")
end

def exec(table_name)
#do something
end
end


lib/tasks/spreadsheet.rake

namespace :spreadsheet do
task :get => :environment do
importer = Spreadsheet::Importer.new
importer.exec
end
end


Error:


rake aborted!

NameError: uninitialized constant
SpreadSheet


/home/vagrant/workspace/ruby/kuwata-summer/lib/tasks/spreadsheet.rake:1:in
<top (required)>


/home/vagrant/workspace/ruby/kuwata-summer/vendor/bundle/ruby/2.3.0
/gems/railties-5.0.0/lib/rails/engine.rb:654:in
block in run_tasks_blocks


/home/vagrant/workspace/ruby/kuwata-summer/vendor/bundle/ruby/2.3.0/gems/railties-5.0.0/lib/rails/engine.rb:654:in
each


/home/vagrant/workspace/ruby/kuwata-summer/vendor/bundle/ruby/2.3.0/gems/railties-5.0.0/lib/rails/engine.rb:654:in
run_tasks_blocks


/home/vagrant/workspace/ruby/kuwata-summer/vendor/bundle/ruby/2.3.0/gems/railties-5.0.0/lib/rails/application.rb:443:in
run_tasks_blocks


/home/vagrant/workspace/ruby/kuwata-summer/vendor/bundle/ruby/2.3.0/gems/railties-5.0.0/lib/rails/engine.rb:457:in
load_tasks


/home/vagrant/workspace/ruby/kuwata-summer/rakefile:6:in
<top (required)>


/home/vagrant/workspace/ruby/kuwata-summer/vendor/bundle/ruby/2.3.0/gems/rake-11.2.2/exe/rake:27:in
<top (required)>


/home/vagrant/.rbenv/versions/2.3.1/bin/bundle:23:in
load


/home/vagrant/.rbenv/versions/2.3.1/bin/bundle:23:in
<main>


(See full trace by running task with --trace)

Answer

Yes..you can add it auto load, but an alternative is to add inside the rake file by "require"

Here is another way,

lib/spreadsheet/importer.rb

module Spreadsheet
    class Importer
      def initialize
        @session = GoogleDrive.saved_session("#{Rails.root}/config/google_drive/config.json")
      end

      def exec(table_name)
        #do something
      end
    end
end

lib/tasks/spreadsheet.rake

You need to incude the file by using 'reqire'

namespace :spreadsheet do
  task :get => :environment do
    require "#{Rails.root}/lib/spreadsheet/importer"  
    importer = Spreadsheet::Importer.new
    importer.exec
  end
end

Happy Coding!!!!!

Thanks.