Class: Addons::Config

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

Class Method Summary collapse

Class Method Details

.initObject



9
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
# File 'lib/addons/config.rb', line 9

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

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

    if File.exists?(filename)
      File.open(filename, 'r') do |file|
        # NOTE: read the ADDONS_APP_ID and ADDONS_APP_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_APP_ID'] and ENV['ADDONS_APP_TOKEN']"

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

  # contact server and look for config
  configUrl = "#{BASE_CONFIG_URL}?app_id=#{ENV['ADDONS_APP_ID']}&app_token=#{ENV['ADDONS_APP_TOKEN']}&source=rubygem"

  begin
    response = URI.parse(configUrl).read

    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_APP_ID'] and ENV['ADDONS_APP_TOKEN']"
  end

end