Sha256: d9eb514eeaa601065525c1d0f6f4d4650e1d9ebb5e9499bf313221fac9dfd57f

Contents?: true

Size: 1.38 KB

Versions: 6

Compression:

Stored size: 1.38 KB

Contents

# frozen_string_literal: true

module LedgerSync
  module Util
    class DotenvUpdator
      attr_reader :file_path

      def initialize(args = {})
        @file_path = args.fetch(:file_path, File.join(Dir.pwd, '.env.local'))
      end

      def update(args = {})
        client = args.fetch(:client)
        prefix = args.fetch(:prefix, "#{client.class.config.root_key.upcase}_")

        to_save = client.ledger_attributes_to_save.dup.stringify_keys

        Tempfile.open(".#{File.basename(file_path)}", File.dirname(file_path)) do |tempfile|
          File.open(file_path).each do |line|
            env_key = line.split('=').first
            client_method = env_key.split(prefix).last.downcase

            if line =~ /\A#{prefix}/ && to_save.key?(client_method)
              env_value = ENV[env_key]
              new_value = to_save.delete(client_method)
              tempfile.puts "#{env_key}=#{new_value}"
              next if env_value == new_value.to_s

              ENV[env_key] = new_value.to_s
              tempfile.puts "# #{env_key}=#{env_value} # Updated on #{Time.now}"
            else
              tempfile.puts line
            end
          end

          to_save.each { |k, v| tempfile.puts(["#{prefix}#{k}".upcase, v].map(&:to_s).join('=')) }

          tempfile.close
          FileUtils.mv tempfile.path, file_path
        end

        Dotenv.load
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
ledger_sync-2.0.0 lib/ledger_sync/util/dotenv_updator.rb
ledger_sync-2.0.0.pre.1 lib/ledger_sync/util/dotenv_updator.rb
ledger_sync-1.8.1 lib/ledger_sync/util/dotenv_updator.rb
ledger_sync-1.8.0 lib/ledger_sync/util/dotenv_updator.rb
ledger_sync-1.7.0 lib/ledger_sync/util/dotenv_updator.rb
ledger_sync-1.6.0 lib/ledger_sync/util/dotenv_updator.rb