Module: Easy::ReferenceData

Defined in:
lib/easy/reference_data/railtie.rb,
lib/easy/reference_data/refresh.rb,
lib/easy/reference_data/version.rb

Defined Under Namespace

Classes: Railtie

Constant Summary collapse

VERSION =
"1.1.0"

Class Method Summary collapse

Class Method Details

.filesObject



43
44
45
46
47
# File 'lib/easy/reference_data/refresh.rb', line 43

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

.load_files(wrap_in_transaction: false) ⇒ Object



31
32
33
34
35
36
37
38
39
# File 'lib/easy/reference_data/refresh.rb', line 31

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

.load_the_filesObject



49
50
51
52
53
54
# File 'lib/easy/reference_data/refresh.rb', line 49

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

.refresh(clazz, unique_attribute_symbol, unique_attribute_value, attributes) ⇒ Object



6
7
8
# File 'lib/easy/reference_data/refresh.rb', line 6

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

.update_or_create(clazz, attributes, options) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/easy/reference_data/refresh.rb', line 10

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!(attributes)
  rescue
    $stderr.puts "Save failed for #{record.class} with attributes #{attributes.inspect}"
    raise
  end

  record
end