耙子流产了! NameError:uninitialized constant甚至添加:enviroment to task

时间:2016-07-20 13:33:16

标签: ruby-on-rails ruby rubygems rake google-spreadsheet-api

我是RoR的新手并尝试通过在lib /电子表格下创建导入器来创建从谷歌电子表格导入数据库的任务。但是rake找不到我的导入器,即使我添加了:根据SOF中的其他一些问题来完成任务的环境。这是我的文件

LIB /电子表格/ 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 /任务/ spreadsheet.rake

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

错误:

  

rake aborted!

     

NameError:未初始化的常量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>

     

(通过使用--trace运行任务查看完整跟踪)

2 个答案:

答案 0 :(得分:0)

资本化很重要。

Spreadsheet已定义; SpreadSheet不是。

这就是为什么您的代码在尝试定义SpreadSheet::Importer时会抛出错误。

......或者至少,基于我所拥有的有限信息,这就是的样子。如果Speadsheet实际上没有在代码中的任何其他地方定义,那么您可以写:

module Spreadsheet # Can be a class, and can instead be SpreadSheet - as long as you're consistent!!
  class Import
    # ...
  end
end

答案 1 :(得分:0)

是..你可以添加它自动加载,但另一种方法是通过“require”在rake文件中添加

这是另一种方式,

LIB /电子表格/ 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 /任务/ spreadsheet.rake

您需要使用'reqire'

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

快乐编码!!!!!

感谢。