Sha256: aedd9d3e097ef7a98e141a7879696f2fd65943c599497a047b5dc837a9fd320a

Contents?: true

Size: 1.29 KB

Versions: 1

Compression:

Stored size: 1.29 KB

Contents

# Populates db with units of measure.
class PopulateOkeiUnits < ActiveRecord::Migration

  # reloads units and their uuids from db/seed/units.json
  def up
    return if Rails.env.test?
    down
    populate_units_from seed
  end

  # deletes all units with their uuids.
  def down
    return if Rails.env.test?
    clear_uuids
    clear_units
  end

  private

  # Parses JSON from db/seed/units.json
  def seed
    @seed ||= begin
      root = File.dirname File.dirname(Okei::Engine.called_from)
      file = File.join(root, "db", "seeds", "units.json")
      JSON.parse(File.read file)
    end
  end

  # Deletes units' uuids.
  def clear_uuids
    list = Uuids::Uuid.where(record_type: "Okei::Unit")
    say_with_time "Removing #{ list.count } uuids" do
      list.delete_all
      left = list.count
      fail "#{ left } uuids left undeleted" if left > 0
    end
  end

  # Deletes units objects.
  def clear_units
    list = Okei::Unit.all
    say_with_time "Removing #{ list.count } units" do
      list.delete_all
      left = list.count
      fail "#{ left } units left undeleted" if left > 0
    end
  end

  # Populates units and their uuids from given JSON
  def populate_units_from(json)
    say_with_time "Adding #{ json.count } units" do
      json.each { |item| Okei::Unit.create! item }
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
okei-1.0.2 db/migrate/20141019072901_populate_okei_units.rb