Class: Launchbox::Config

Inherits:
Object
  • Object
show all
Defined in:
lib/launchbox/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
72
# File 'lib/launchbox/config.rb', line 9

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

  puts "checking ENV['LAUNCHBOX_USER_EMAIL'] and ENV['LAUNCHBOX_USER_TOKEN']"

  if ENV['LAUNCHBOX_USER_EMAIL'] == nil
    return false, "Error: ENV['LAUNCHBOX_USER_EMAIL'] must be defined"
  elsif ENV['LAUNCHBOX_USER_TOKEN'] == nil
    return false, "Error: ENV['LAUNCHBOX_USER_TOKEN'] must be defined"
  end

  # contact server and look for config
  configUrl = "#{BASE_CONFIG_URL}?user_email=#{ENV['LAUNCHBOX_USER_EMAIL']}&user_token=#{ENV['LAUNCHBOX_USER_TOKEN']}"

  begin
    response = URI.parse(configUrl).read

    json = JSON.parse(response)

    # FIXME: LAUNCHBOX_APP_ID -- json[0] is hardcoding the first app.
    app = json[0]

    # gitignore config/application.yml so we aren't storing sensitive info in .git
    # TODO: replace figaro with figaro-launchbox and application.yml with launchbox.yml
    gitignore = Rails.root.join('.gitignore')
    if File.readlines(gitignore).grep(/config\/application.yml/).size == 0
      File.open(gitignore, 'a') do |file|
        file.puts 'config/application.yml'
      end
    end

    figaro = Rails.root.join('Gemfile')
    if File.readlines(figaro).grep(/gem 'figaro'/).size == 0
      File.open(figaro, 'a') do |file|
        file.puts ""
        file.puts "gem 'figaro' # Launchbox dependency"
      end
    end

    # 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
      app.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 Launchbox. Be sure to set ENV['LAUNCHBOX_USER_EMAIL'] and ENV['LAUNCHBOX_USER_TOKEN']"
  end

end