【问题标题】:Undefined Method for 'NilClass''NilClass' 的未定义方法
【发布时间】:2021-10-25 13:59:06
【问题描述】:

我知道这是一个经常被问到的问题,但是尽管在这里研究了几个小时,但我一直在努力解决这个问题。我正在尝试将 .xlsx 文档上传到我的 AWS S3 存储桶,但是我收到此错误:

Error while uploading the file '' to the bucket '': undefined method `bucket' for nil:NilClass

但是,我已经查看了我的代码,并且该错误对我来说并不明显。我将在下面附上相关代码。

       attr_reader :year,  :month, :data, :bucket_name, :file_name, :path

      def initialize(year:, month:, data:)
        @year = year
        @month = month
        @data = data

      end

      def call
        REPORTS.each do |report|
          data =  generate_report_data(report)
          tmp_path = report_tmp_path(report)
          save_report_to_file(data: data, path: tmp_path)
          upload_file_to_bucket?(bucket_name, file_name, path )
        end
      end


      def generate_report_data(report)
        report_class = "Accounting::Datev::Reports::#{report.to_s.camelize}".constantize
        report_class.new(year: year, month: month).call
      end

      def save_report_to_file(data:, path:)
        prepare_dir(path)
        Accounting::Datev::Utils::ExcelGenerator.new(data: data, path: path).call
      end


      def s3_resource
        @s3_resource ||= ::Aws::S3::Resource.new(access_key_id: Settings.aws_pair&.app_key_id,
                                                 secret_access_key: Settings.aws_pair&.app_secret_key,
                                                 region: Settings.aws_pair&.s3_region)
      end

      def BUCKET_NAME
        @bucket_name = s3.bucket('textract-console-eu-central-1-3469d743-084a-020378550')

      end

      def upload_file_to_bucket?( file_name, path, bucket_name)
        s3 = @s3_resource
        obj = s3.bucket(bucket_name).object('/tmp/test.xls')
        obj.upload_file(path)

        true
        rescue StandardError => e
          puts "Error while uploading the file '#{file_name}' to the bucket '#{bucket_name}': #{e.message}"

      end


      def report_tmp_path(report)
        "/tmp/reports/#{year}/#{month}/#{report}.xls"
      end

      def prepare_dir(path)
        dir = File.dirname(path)
        FileUtils.mkdir_p(dir)
      end


    end
  end
end

【问题讨论】:

    标签: ruby amazon-s3


    【解决方案1】:

    很遗憾,您没有说明在哪一行引发了异常,也没有提供完整的堆栈跟踪。

    但乍一看,有这个bucket调用:

    def BUCKET_NAME
      @bucket_name = s3.bucket(...)
    end
    

    在这里,您在s3 上调用bucket,但您的代码中不存在s3 变量,也没有s3 方法。因此,该BUCKET_NAME 方法的所有调用都必须失败。

    【讨论】:

    • 这将是obj = s3.bucket(bucket_name)这一行,因为前一行是s3 = @s3_resource,它没有调用BUCKET_NAME(这是一个糟糕的方法名称,会因NoMethodError而失败), @s3_resource 将是 nil
    猜你喜欢
    • 2014-06-01
    • 1970-01-01
    • 2015-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多