Sha256: 21ac9a8fcfcd086ffa6988a1e076810bd691254095dd1faceb655cc3fd2b6a6d

Contents?: true

Size: 1.39 KB

Versions: 4

Compression:

Stored size: 1.39 KB

Contents

require 'json'

module Polyblock
  class Block < ActiveRecord::Base

    belongs_to :contentable, :polymorphic => true, :dependent => :destroy

    def self.import(pbs)
      outputs = pbs.map do |pb|
        block = fetch_or_initialize pb[:name]
        block.content = pb[:content] if pb.key?(:content) && pb[:content].present? && pb[:content] != block.content
        block.save
      end
      outputs.include?(false)
    end

    def self.export
      output = all.as_json(:except => [:id, :created_at, :updated_at])
      puts ""
      puts "Run the following in Rails Console on the remote server:"
      puts ""
      puts "Polyblock::Block.import(#{output})"
      puts ""
    end

    def to_s
      content
    end

    def present?
      !nil? && content.present?
    end

    def blank?
      nil? || content.blank?
    end

    def self.fetch_or_initialize(name)
      if name.is_a? Block
        name
      else
        matches = where :name => name
        if matches.any?
          matches.first
        else
          new({:name => name})
        end
      end
    end
    def self.fetch_or_create(name)
      pb = fetch_or_initialize(name)
      pb.save if pb.new_record?
      pb
    end

    def self.next_id
      any? ? maximum(:id).next : 1
    end
    def self.random_id
      o = [('a'..'z'), ('A'..'Z')].map { |i| i.to_a }.flatten
      (0...50).map { o[rand(o.length)] }.join
    end

  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
polyblock-0.6.4 app/models/polyblock/block.rb
polyblock-0.6.3 app/models/polyblock/block.rb
polyblock-0.6.2 app/models/polyblock/block.rb
polyblock-0.6.1 app/models/polyblock/block.rb