Class: Plotlyrb::PlotImage

Inherits:
Object
  • Object
show all
Defined in:
lib/plotlyrb/plot_image.rb

Defined Under Namespace

Classes: AsyncJob, AsyncJobResult, SpecPath

Constant Summary collapse

VALID_IMAGE_FORMATS =
[:png, :svg, :pdf, :eps]

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(headers) ⇒ PlotImage

Returns a new instance of PlotImage.



9
10
11
12
13
# File 'lib/plotlyrb/plot_image.rb', line 9

def initialize(headers)
  @headers = headers
  @https = Net::HTTP.new(ApiV2::IMAGES.host, ApiV2::IMAGES.port)
  @https.use_ssl = true
end

Class Method Details

.plot_images(headers, spec_paths, timeout, retries) ⇒ Object

Given an array of SpecPaths, run each plot_image request in a separate thread, wait timeout for each, then return AsyncJobResults for any inputs that failed after the given number of retries



73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/plotlyrb/plot_image.rb', line 73

def self.plot_images(headers, spec_paths, timeout, retries)
  raise 'Retries must be an integer >= 0' unless (retries.class == Fixnum && retries >= 0)
  return [] if spec_paths.empty?

  input_results = spec_paths.map { |sp| AsyncJobResult.new(false, 'not run yet', sp) }
  (0..retries).to_a.inject(input_results) { |ajrs, _|
    # While you might be tempted to fuse these map calls, we want all the jobs to get started
    # before we start joining them, so don't do that.
    rs = ajrs.map { |ajr| AsyncJob.from_spec_path(PlotImage.new(headers), ajr.spec_path, timeout) }.
              map(&:join).
              reject(&:success)
  }
end

Instance Method Details

#plot_image(plot_image_spec, image_path) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/plotlyrb/plot_image.rb', line 15

def plot_image(plot_image_spec, image_path)
  raise 'No :format key in spec' unless plot_image_spec.has_key?(:format)
  raise 'No :figure key in spec' unless plot_image_spec.has_key?(:figure)
  raise ':data key not found at {:figure => {:data => ...}}' unless plot_image_spec[:figure].has_key?(:data)

  image_format = plot_image_spec[:format]
  raise "Image format #{image_format} not supported" unless VALID_IMAGE_FORMATS.include?(image_format.to_sym)

  request = Net::HTTP::Post.new(ApiV2::IMAGES.path, @headers)
  request.body = plot_image_spec.to_json
  response = Response.from_http_response(@https.request(request))
  IO.binwrite(image_path, response.body) if response.success
  response
end