Sha256: 6c639e88cfa28feff863a8ce4cfd27ba1db71c970af9242071ad078327f10e82

Contents?: true

Size: 1.44 KB

Versions: 4

Compression:

Stored size: 1.44 KB

Contents

require 'json'

module Polyblock
  class Block < ActiveRecord::Base

    belongs_to :contentable, :polymorphic => true

    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 system?
      self.contentable.nil?
    end

    def self.fetch_or_initialize(name)
      if name.is_a? Block
        name
      elsif name.is_a? String
        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.7.2 app/models/polyblock/block.rb
polyblock-0.7.1 app/models/polyblock/block.rb
polyblock-0.7.0 app/models/polyblock/block.rb
polyblock-0.6.7 app/models/polyblock/block.rb