Class: Addons::Config

Inherits:
Object
  • Object
show all
Defined in:
lib/addons/config.rb

Class Method Summary collapse

Class Method Details

.initObject



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
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
# File 'lib/addons/config.rb', line 10

def self.init
  puts "Initializing Addons::Config"

  if ENV['ADDONS_API_ID'].nil? or ENV['ADDONS_API_ID'] == ""
    filename = Rails.root.join('config', 'application.yml')

    if File.exists?(filename)
      File.open(filename, 'r') do |file|
        # NOTE: read the ADDONS_API_ID and ADDONS_AUTH_TOKEN from application.yml and set ENV vars.

        file.each_line do |line|
          matches = line.match(/(.*): (.*)/)

          env_var, value = matches[1], matches[2]
          ENV[env_var] = value
        end
      end
    end
  end

  puts "checking ENV['ADDONS_API_ID'] and ENV['ADDONS_AUTH_TOKEN']"

  if ENV['ADDONS_API_ID'] == nil
    puts "Error: ENV['ADDONS_API_ID'] must be defined"
    return false, "Error: ENV['ADDONS_API_ID'] must be defined"
  elsif ENV['ADDONS_AUTH_TOKEN'] == nil
    puts "Error: ENV['ADDONS_AUTH_TOKEN'] must be defined"
    return false, "Error: ENV['ADDONS_AUTH_TOKEN'] must be defined"
  end

  # contact server and look for config
  configUrl = "#{BASE_CONFIG_URL}?source=rubygem"

  begin

    uri = URI.parse(configUrl)

    http = Net::HTTP.new(uri.host, uri.port)
    http.use_ssl = true
    request = Net::HTTP::Get.new(uri.request_uri)
    request.basic_auth(ENV['ADDONS_API_ID'], ENV['ADDONS_AUTH_TOKEN'])
    response = http.request(request).body

    services = JSON.parse(response)

    # write config/application.yml to load env vars on startup
    filename = Rails.root.join('config', 'application.yml')

    # NOTE: 'w' overwrites the previous file!
    File.open(filename, 'w') do |file|
      # set environment variables for each service
      services.each do |service|
        service['env_vars'].each do |key, value|
          puts "setting environment variable #{key}"

          # add new vars to application.yml for the restart
          file.puts "#{key}: #{value}"

          # add new vars to this instance
          ENV[key] = value
        end
      end
    end
    return true, "Success"

  rescue OpenURI::HTTPError => ex
    return false, "Error: Unauthorized use of Addons. Be sure to set ENV['ADDONS_API_ID'] and ENV['ADDONS_AUTH_TOKEN']"
  end

end