Sha256: fca15e334b91420cadbd6032ffce125c2b2b5c10d68e9f35a636f9e113b1a5ff

Contents?: true

Size: 1.3 KB

Versions: 2

Compression:

Stored size: 1.3 KB

Contents

require 'yinx'
require 'yinx_sql/stack'
require 'yinx_sql/book'
require 'yinx_sql/note'
require 'yinx_sql/tag'

module Yinx
  module SQL
    class Batch < ActiveRecord::Base
      has_many :tags, dependent: :destroy
      has_many :stacks, dependent: :destroy
      has_many :books, dependent: :destroy

      def self.insert notes
        batch = Batch.new

        stacks = Hash.new do |h, name|
          stack = Stack.new name: name
          batch.stacks << stack
          h[name] = stack
        end

        books = Hash.new do |h, stack_book|
          b = Book.new(name: stack_book[1])
          batch.books << b
          stacks[stack_book[0]].books << b
          h[stack_book] = b
        end

        tags = Hash.new do |h, name|
          tag = Tag.new name: name
          batch.tags << tag
          h[name] = tag
        end

        notes.each do |note|
          n = Note.new(title: note.title,
                       content_length: note.contentLength,
                       created_at: note.created_at,
                       updated_at: note.updated_at)

          book = books[[note.stack, note.book]]
          book.notes << n

          note.tags.each do |tag_name|
            tag = tags[tag_name]
            tag.notes << n
          end
        end

        batch.save
      end

    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
yinx_sql-0.1.1 lib/yinx_sql/batch.rb
yinx_sql-0.1.0 lib/yinx_sql/batch.rb