Class: BetterBatch::ActiveRecord::Interface

Inherits:
Object
  • Object
show all
Defined in:
lib/better_batch/active_record/interface.rb

Instance Method Summary collapse

Constructor Details

#initialize(model) ⇒ Interface

Returns a new instance of Interface.



10
11
12
13
# File 'lib/better_batch/active_record/interface.rb', line 10

def initialize(model)
  @builder = Query.new(model)
  @model = model
end

Instance Method Details

#select(data, unique_by:, returning:) ⇒ Object



42
43
44
45
46
47
48
# File 'lib/better_batch/active_record/interface.rb', line 42

def select(data, unique_by:, returning:)
  Transform.assert_inputs_ok!(data, unique_by:)
  select_data = data.map { |datum| datum.slice(*unique_by) }
  query = builder.build(select_data, unique_by:, returning:)
  result = exec_query(:select, query, select_data)
  Transform.build_return(returning, result.rows, query)
end

#set_selected_pk(data, unique_by:) ⇒ Object



59
60
61
62
63
64
65
66
67
68
# File 'lib/better_batch/active_record/interface.rb', line 59

def set_selected_pk(data, unique_by:)
  if block_given?
    with_selected_pk(data, unique_by:) do |row, pk|
      row[primary_key] = pk
      yield row
    end
  else
    set_selected_pk_map(data, unique_by:)
  end
end

#set_upserted_pk(data, unique_by:, except: nil) ⇒ Object



31
32
33
34
35
36
37
38
39
40
# File 'lib/better_batch/active_record/interface.rb', line 31

def set_upserted_pk(data, unique_by:, except: nil)
  if block_given?
    with_upserted_pk(data, unique_by:, except:) do |row, pk|
      row[primary_key] = pk
      yield row
    end
  else
    set_upserted_pk_map(data, unique_by:, except:)
  end
end

#upsert(data, unique_by:, except: nil, returning: nil) ⇒ Object



15
16
17
18
19
20
# File 'lib/better_batch/active_record/interface.rb', line 15

def upsert(data, unique_by:, except: nil, returning: nil)
  upsert_data = Transform.slice_upsert(data, except:)
  query = builder.build(upsert_data, unique_by:, returning:)
  result = exec_query(:upsert, query, upsert_data)
  Transform.build_return(returning, result.rows, query)
end

#with_selected_pk(data, unique_by:) ⇒ Object



50
51
52
53
54
55
56
57
# File 'lib/better_batch/active_record/interface.rb', line 50

def with_selected_pk(data, unique_by:, &)
  selected = select(data, unique_by:, returning: primary_key)
  if block_given?
    data.zip(selected, &)
  else
    data.zip(selected)
  end
end

#with_upserted_pk(data, unique_by:, except: nil) ⇒ Object



22
23
24
25
26
27
28
29
# File 'lib/better_batch/active_record/interface.rb', line 22

def with_upserted_pk(data, unique_by:, except: nil, &)
  upserted = upsert(data, unique_by:, except:, returning: primary_key)
  if block_given?
    data.zip(upserted, &)
  else
    data.zip(upserted)
  end
end