Class: Mindee::Input::LocalResponse

Inherits:
Object
  • Object
show all
Defined in:
lib/mindee/input/local_response.rb

Overview

Response loaded locally.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(input_file) ⇒ LocalResponse

Returns a new instance of LocalResponse.

Parameters:

  • input_file (File, Tempfile, IO, StringIO, String, Pathname)

    The input file, which can be a StringIO.



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/mindee/input/local_response.rb', line 16

def initialize(input_file)
  case input_file
  when IO, StringIO, File, Tempfile
    str_stripped = input_file.read.gsub(%r{[\r\n]}, '')
    @file = StringIO.new(str_stripped)
    @file.rewind
  when Pathname, String
    @file = if Pathname(input_file).exist?
              StringIO.new(File.read(input_file, encoding: 'utf-8').gsub(%r{[\r\n]}, ''))
            else
              StringIO.new(input_file.gsub(%r{[\r\n]}, ''))
            end
    @file.rewind
  else
    raise "Incompatible type for input '#{input_file.class}'."
  end
end

Instance Attribute Details

#fileObject (readonly)

Returns the value of attribute file.



13
14
15
# File 'lib/mindee/input/local_response.rb', line 13

def file
  @file
end

Class Method Details

.process_secret_key(secret_key) ⇒ String

Processes the secret key

Parameters:

  • secret_key (String)

    the secret key as plain text.

Returns:

  • (String)


47
48
49
# File 'lib/mindee/input/local_response.rb', line 47

def self.process_secret_key(secret_key)
  secret_key.is_a?(String) ? secret_key.encode('utf-8') : secret_key
end

Instance Method Details

#as_hashHash

Returns the file as a hash.

Returns:

  • (Hash)


36
37
38
39
40
41
42
# File 'lib/mindee/input/local_response.rb', line 36

def as_hash
  @file.rewind
  file_str = @file.read
  JSON.parse(file_str, object_class: Hash)
rescue JSON::ParserError
  raise "File is not a valid dict. #{file_str}"
end

#get_hmac_signature(secret_key) ⇒ String

Parameters:

  • secret_key (String)

    [String] Secret key, either a string or a byte/byte array.

Returns:

  • (String)


53
54
55
56
57
58
59
60
61
62
# File 'lib/mindee/input/local_response.rb', line 53

def get_hmac_signature(secret_key)
  algorithm = OpenSSL::Digest.new('sha256')
  begin
    @file.rewind
    mac = OpenSSL::HMAC.hexdigest(algorithm, self.class.process_secret_key(secret_key), @file.read)
  rescue StandardError
    raise 'Could not get HMAC signature from payload.'
  end
  mac
end

#valid_hmac_signature?(secret_key, signature) ⇒ Boolean

Parameters:

  • secret_key (String)

    Secret key, either a string or a byte/byte array.

  • signature (String)

Returns:

  • (Boolean)


67
68
69
# File 'lib/mindee/input/local_response.rb', line 67

def valid_hmac_signature?(secret_key, signature)
  signature == get_hmac_signature(secret_key)
end