Sha256: f64997744654704f326065d23e46a5d476e1fa98cefb38124b018ab990ef604e

Contents?: true

Size: 1.53 KB

Versions: 1

Compression:

Stored size: 1.53 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 = {}) # rubocop:disable Metrics/CyclomaticComplexity,Metrics/PerceivedComplexity
        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|
          if File.file?(file_path)
            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
          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

1 entries across 1 versions & 1 rubygems

Version Path
ledger_sync-2.0.1 lib/ledger_sync/util/dotenv_updator.rb