Sha256: 8e383bda718fb74f3d461c8b8f6a18c9dd53087594455855a42891693ab8ea5a

Contents?: true

Size: 1.47 KB

Versions: 1

Compression:

Stored size: 1.47 KB

Contents

require 'active_support'

module Easy
  module ReferenceData

    def self.refresh(clazz, unique_attribute_symbol, unique_attribute_value, attributes)
      self.update_or_create(clazz, attributes.merge(unique_attribute_symbol => unique_attribute_value), keys: [unique_attribute_symbol])
    end

    def self.update_or_create(clazz, attributes, options)
      unique_attribute_keys = options.fetch(:keys)

      record = clazz.where(attributes.slice(*unique_attribute_keys)).first_or_initialize

      if record.new_record?
        $stderr.puts "..creating #{clazz}(#{attributes.slice(*unique_attribute_keys)})"
      else
        $stderr.puts "..updating #{clazz}(#{attributes.slice(*unique_attribute_keys)})"
      end

      begin
        record.update!(attributes)
      rescue
        $stderr.puts "Save failed for #{record.class} with attributes #{attributes.inspect}"
        raise
      end

      record
    end

    def self.load_files(wrap_in_transaction: false)
      if wrap_in_transaction
        ActiveRecord::Base.transaction do
          load_the_files
        end
      else
        load_the_files
      end
    end

    private_class_method

    def self.files
      files = Dir[File.join(Rails.root, 'db', 'reference', '*.rb')].sort
      files += Dir[File.join(Rails.root, 'db', 'reference', Rails.env, '*.rb')].sort
      files
    end

    def self.load_the_files
      files.each do |file|
        puts "Populating reference #{file}"
        load file
      end
    end

  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
easy_reference_data-1.2.0 lib/easy/reference_data/refresh.rb