Class: Apiary::Command::Fetch

Inherits:
Object
  • Object
show all
Defined in:
lib/apiary/command/fetch.rb

Overview

Retrieve blueprint from apiary

Instance Method Summary collapse

Constructor Details

#initialize(opts) ⇒ Fetch

Returns a new instance of Fetch.



12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/apiary/command/fetch.rb', line 12

def initialize(opts)
  @options = OpenStruct.new(opts)
  @options.api_host     ||= 'api.apiary.io'
  @options.api_name     ||= false
  @options.api_key      ||= ENV['APIARY_API_KEY']
  @options.proxy        ||= ENV['http_proxy']
  @options.headers      ||= {
    accept: 'text/html',
    content_type: 'text/plain',
    authentication: "Token #{@options.api_key}",
    user_agent: Apiary.user_agent
  }
end

Instance Method Details

#executeObject



26
27
28
29
30
31
32
# File 'lib/apiary/command/fetch.rb', line 26

def execute
  response = fetch_from_apiary

  return unless response.instance_of? String

  puts response
end

#fetch_from_apiaryObject



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/apiary/command/fetch.rb', line 34

def fetch_from_apiary
  unless @options.api_name
    abort 'Please provide an api-name option (subdomain part from your http://docs.<api-name>.apiary.io/)'
  end

  unless @options.api_key
    abort 'API key must be provided through environment variable APIARY_API_KEY. Please go to https://login.apiary.io/tokens to obtain it.'
  end

  response = query_apiary

  if @options.output
    write_generated_path(response['code'], @options.output)
  else
    response['code']
  end
end

#query_apiaryObject



52
53
54
55
56
57
58
59
60
61
62
# File 'lib/apiary/command/fetch.rb', line 52

def query_apiary
  url = "https://#{@options.api_host}/blueprint/get/#{@options.api_name}"
  RestClient.proxy = @options.proxy

  begin
    response = RestClient.get url, @options.headers
  rescue RestClient::Exception => e
    abort "Apiary service responded with an error: #{e.message}"
  end
  JSON.parse response.body
end

#write_generated_path(data, outfile) ⇒ Object



64
65
66
67
68
# File 'lib/apiary/command/fetch.rb', line 64

def write_generated_path(data, outfile)
  File.open(outfile, 'w') do |file|
    file.write(data)
  end
end