update dotenv-rails and attempt to make cap sync:db:down work with remote .env files

Andrew Cantino 11 years ago
parent
commit
0b0d809ede
2 changed files with 33 additions and 4 deletions
  1. 3 3
      Gemfile.lock
  2. 30 1
      lib/capistrano/sync.rb

+ 3 - 3
Gemfile.lock

@@ -63,9 +63,9 @@ GEM
63 63
       railties (>= 3.2.6, < 5)
64 64
       warden (~> 1.2.3)
65 65
     diff-lcs (1.2.4)
66
-    dotenv (0.8.0)
67
-    dotenv-rails (0.8.0)
68
-      dotenv (= 0.8.0)
66
+    dotenv (0.9.0)
67
+    dotenv-rails (0.9.0)
68
+      dotenv (= 0.9.0)
69 69
     em-http-request (1.0.3)
70 70
       addressable (>= 2.2.3)
71 71
       cookiejar

+ 30 - 1
lib/capistrano/sync.rb

@@ -1,5 +1,6 @@
1 1
 require 'yaml'
2 2
 require 'pathname'
3
+require 'dotenv'
3 4
 
4 5
 # Edited by Andrew Cantino.  Based on: https://gist.github.com/339471
5 6
 
@@ -99,6 +100,28 @@ namespace :sync do
99 100
     return database["#{db}"]['username'], database["#{db}"]['password'], database["#{db}"]['database'], database["#{db}"]['host']
100 101
   end
101 102
 
103
+  # Used by remote_database_config to parse the remote .env file.  Depends on the dotenv-rails gem.
104
+  class RemoteEnvLoader < Dotenv::Environment
105
+    def initialize(data)
106
+      @data = data
107
+      load
108
+    end
109
+
110
+    def with_loaded_env
111
+      begin
112
+        saved_env = ENV.to_hash.dup
113
+        ENV.update(self)
114
+        yield
115
+      ensure
116
+        ENV.replace(saved_env)
117
+      end
118
+    end
119
+
120
+    def read
121
+      @data.split("\n")
122
+    end
123
+  end
124
+
102 125
   #
103 126
   # Reads the database credentials from the remote config/database.yml file
104 127
   # +db+ the name of the environment to get the credentials for
@@ -106,7 +129,13 @@ namespace :sync do
106 129
   #
107 130
   def remote_database_config(db)
108 131
     remote_config = capture("cat #{current_path}/config/database.yml")
109
-    database = YAML::load(remote_config)
132
+    remote_env = capture("cat #{current_path}/.env")
133
+
134
+    database = nil
135
+    RemoteEnvLoader.new(remote_env).with_loaded_env do
136
+      database = YAML::load(ERB.new(remote_config).result)
137
+    end
138
+
110 139
     return database["#{db}"]['username'], database["#{db}"]['password'], database["#{db}"]['database'], database["#{db}"]['host']
111 140
   end
112 141