Class: Cloudfront::Generators::InstallGenerator

Inherits:
Rails::Generators::Base
  • Object
show all
Defined in:
lib/thesis_cloudfront/install_generator.rb

Instance Method Summary collapse

Instance Method Details

#installObject



7
8
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
# File 'lib/thesis_cloudfront/install_generator.rb', line 7

def install
  append_to_file "Gemfile" do
    "\ngem 'rack-cors'"
  end

  heroku_app_name = ask("whats the name of this heroku app?")
  file = `heroku domains -a #{heroku_app_name} --csv`
  file&.gsub!(/===.+|.+\.herokuapp.com/, '').strip
  domains = []

  if file
    CSV.parse(file, headers: true).each do |x|
      if x['Domain Name']
        domains << '      /https:\/\/' + "#{x['Domain Name']}/"
        domains << '      /http:\/\/' + "#{x['Domain Name']}/"
      end
    end
  end

  create_file "config/initializers/rack_cors.rb" do
      ["Rails.application.config.middleware.insert_before 0, Rack::Cors do",
      "  allow do",
      "    origins [",
      "      /https:\\/\\/#{heroku_app_name}.herokuapp.com/,",
      "      /http:\\/\\/#{heroku_app_name}.herokuapp.com/,",
      "      /https:\\/\\/#{heroku_app_name}-pr-\w+.herokuapp.com/,",
      "      /http:\\/\\/#{heroku_app_name}-pr-\w+.herokuapp.com/,", domains.join(",\n"),
      "    ]",
      "    resource '/assets/*', headers: :any, methods: [:get, :head, :options]",
      "  end",
      "end"].join("\n")
  end

  create_file "config/initializers/cloudfront.rb" do
    ["ActionController::Base.asset_host = ENV['CLOUDFRONT_URL']", 
     "config.public_file_server.headers = {",
     "    'Cache-Control' => 'public, max-age=2592000',",
     "    \"Expires\" => \"\#{30.days.from_now.to_formatted_s(:rfc822)}\"",
     "  }"].join("\n")
  end

  inside Rails.root do
    run "bundle install"
  end

  `heroku config:set CLOUDFRONT_URL=#{cloudfront_url} --app #{heroku_app_name}`
end