user16741832
user16741832

Reputation:

Proper usage of 'end_with?'?

I'm attempting to gather all files in my local directory with a .xlsx file format and pull them into my AWS S3 Bucket, however, my method for doing that

attr_reader :bucket, :object_key, :input_file_path

    def initialize(bucket:, object_key:, input_file_path:)
      @bucket = bucket
      @object_key = object_key
      @input_file_path = input_file_path
    end

    def call
      return unless input_file_path.end_with?(".xslx")
      object = s3_resource.bucket(bucket).object(object_key)
      object.upload_file(input_file_path)
    end

returns me

[5] pry(main)> Accounting::Datev::Utils::ExcelUtil.new(bucket: nil,  object_key:nil,  input_file_path: nil).call
NoMethodError: undefined method `end_with?' for nil:NilClass

Am I using end_with? incorrectly?

Upvotes: 0

Views: 131

Answers (1)

Jake Worth
Jake Worth

Reputation: 5852

As @razvans points out, the error message here is great.

The Error

You're initializing your object with input_file_path: nil, and then inside of call you're checking if @input_file_path (set to input_file_path in the initializer, AKA nil) ends with a string.

There is no .end_with? method on nil. That's causing the NoMethodError error.

The Solution

You could guard against nil in your end_with? call, or give it a default value in the initializer.

Upvotes: 2

Related Questions