Class: Heathen::Client

Inherits:
Object
  • Object
show all
Extended by:
Interface
Defined in:
lib/heathen-client.rb,
lib/heathen/client/version.rb,
lib/heathen/client/response.rb,
lib/heathen/client/interface.rb

Defined Under Namespace

Modules: Interface Classes: Response

Constant Summary collapse

DEFAULT_BASE_URI =
'http://localhost:9292'
VERSION =
"1.1.1"

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Interface

doc, ocr, pdf

Constructor Details

#initialize(options = { }) ⇒ Client

Returns a new instance of Client.



27
28
29
# File 'lib/heathen-client.rb', line 27

def initialize(options = { })
  @base_uri = URI.parse(options.fetch(:base_uri, DEFAULT_BASE_URI))
end

Class Method Details

.clientObject



18
19
20
# File 'lib/heathen-client.rb', line 18

def client
  @client ||= new
end

.client=(c) ⇒ Object



22
23
24
# File 'lib/heathen-client.rb', line 22

def client=(c)
  @client = c
end

Instance Method Details

#convert(action, options) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/heathen-client.rb', line 31

def convert(action, options)

  options.merge!(action: action)
  headers = {
    content_type: :json,
    accept: :json
  }

  # in Rails, Hash has a read method, but this makes
  # RestClient think that the hash is a File.
  #
  # this fixes compatitbility with Rails without
  # needing to patch RestClient
  class << options
    def respond_to?(*args)
      args.first.to_s == 'read' ? false : super
    end
  end

  RestClient.post(@base_uri.to_s + '/convert', options, headers) do |response|
    Response.new(self, response.body)
  end
end

#download(url, options) ⇒ Object



55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/heathen-client.rb', line 55

def download(url, options)
  file = options.fetch(:file, nil)
  dir  = file ? nil : Pathname(options.fetch(:dir))

  if dir && !dir.directory?
    raise "Not a directory: #{dir}"

  elsif !file || (file && !file.respond_to?(:write))
    raise 'File or directory must be given.'
  end

  RestClient.get((@base_uri + URI.parse(url).path).to_s) do |response|
    disposition = response.headers[:content_disposition]
    filename    = URI.decode(disposition.match(/filename\=\"(.+?)\"/)[1])

    if dir
      File.open(dir + filename, "wb") { |f| f.write(response.body) }
    else
      file.write(response.body)
    end

    if file
      file.close
    end
  end
end