Module: Dagable::Migrations::Helper

Defined in:
lib/dagable/migrations/helper.rb

Overview

Convenience methods for seeding dagable records inside migrations or seed files. Wraps creation and edge wiring in a single transaction.

Usage

Dagable::Migrations::Helper.create_dagable_item(
  Category,
  { name: "Electronics" },
  children: [phones, laptops],
)

Class Method Summary collapse

Class Method Details

.create_dagable_item(model, attributes, parents: [], children: []) ⇒ ActiveRecord::Base

Creates a dagable record and wires up parent/child edges in one transaction.

Parameters:

  • model (Class)

    the dagable ActiveRecord model class

  • attributes (Hash)

    attributes to pass to model.create!

  • parents (Array) (defaults to: [])

    parent nodes or IDs to attach

  • children (Array) (defaults to: [])

    child nodes or IDs to attach

Returns:

  • (ActiveRecord::Base)

    the created record



26
27
28
29
30
31
32
33
34
35
# File 'lib/dagable/migrations/helper.rb', line 26

def create_dagable_item(model, attributes, parents: [], children: [])
  ActiveRecord::Base.transaction do
    item = model.create!(attributes)

    Array(parents).each { |parent| item.add_parent(retrieve_item(model, parent)) }
    Array(children).each { |child| item.add_child(retrieve_item(model, child)) }

    item
  end
end

.retrieve_item(model, reference) ⇒ ActiveRecord::Base

Resolves a reference to a dagable record. Accepts either a model instance or an integer ID.

Parameters:

  • model (Class)

    the dagable ActiveRecord model class

  • reference (ActiveRecord::Base, Integer)

    the record or its ID

Returns:

  • (ActiveRecord::Base)

Raises:

  • (ArgumentError)

    if the reference type is unsupported



44
45
46
47
48
49
50
# File 'lib/dagable/migrations/helper.rb', line 44

def retrieve_item(model, reference)
  case reference
  when model then reference
  when Integer then model.find(reference)
  else raise ArgumentError, "Invalid dagable item reference"
  end
end