Sha256: ccc160179db719720a6a0bbbf10b5997b63426eb1a59e257c5fa30e1c8136442

Contents?: true

Size: 877 Bytes

Versions: 2

Compression:

Stored size: 877 Bytes

Contents

require 'rails'
require 'active_record'

require 'seed_box/version'
require 'seed_box/railtie'

module SeedBox
  def seed(model, find_or_create_by, update_with = {})
    record = model.where(find_or_create_by).first_or_initialize

    record.update(update_with)

    handle_errors(record, find_or_create_by, update_with)
  end

  def seed_once(model, find_or_create_by, create_with = {})
    return if model.where(find_or_create_by).exists?

    seed(model, find_or_create_by, create_with)
  end

  def seed_file(name)
    File.new(Rails.root.join('db/seeds').join(name))
  end

  private

  def handle_errors(record, find_or_create_by, update_with)
    return record if record.valid?

    raise "Couldn't save #{record.class} " +
      "(#{record.errors.full_messages.join(', ')}) with provided data: " +
      "#{find_or_create_by.inspect}, #{update_with.inspect}"
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
seed_box-0.4.0 lib/seed_box.rb
seed_box-0.3.0 lib/seed_box.rb