Sha256: 2d377c0246b839292952e947ab5b6559a03dae3780c8ae4a58f00caf409ca110

Contents?: true

Size: 1.88 KB

Versions: 10

Compression:

Stored size: 1.88 KB

Contents

module Writefully
  module Tools
    class Pencil
      include Celluloid

      attr_reader :resource, :content, :asset, :index, :site_id, :asset

      class ContentModelNotFound < StandardError; end
      class SomeAssetsNotUploaded < StandardError; end

      def initialize(index)
        @site_id  = Site.where(slug: index[:site]).first.id
        @index    = index
        @content  = Content.new(index)
        @asset    = Asset.new(index)
      end

      def perform
        assets_uploaded = upload_assets.map(&:value).compact
        written_to_db   = future.write if can_update_db?(assets_uploaded)
        terminate if written_to_db.value
      end

      def computed_attributes
        content.meta.merge({ 
          "content" => asset.convert_for(content.body),
          "details" => asset.convert_for(content.details)
        })
      end

      def write
        compute_type.by_site(site_id).where(slug: content.slug)
                      .first_or_initialize
                        .update_attributes(computed_attributes)
      ensure 
        ::ActiveRecord::Base.clear_active_connections! if defined?(::ActiveRecord)
      end
      
      def upload_assets
        asset.names.map do |name|
          Celluloid::Actor[:pigeons].future.upload(asset.endpoint, asset.path, name)
        end
      end

      def can_update_db? uploaded
        if asset.names.count == uploaded.count
          true
        else 
          raise SomeAssetsNotUploaded, "Some assets was not uploaded"
        end
      end

    private

      def compute_type
        index[:resource].classify.constantize
      rescue NameError
        fallback_type
      end

      def fallback_type
        if index[:resource] == "posts"
          "Writefully::Post".constantize
        else 
          raise ContentModelNotFound, "Model #{index[:resource].classify} was not found"
        end
      end
      
    end
  end
end

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
writefully-0.4.10 lib/writefully/tools/pencil.rb
writefully-0.4.8 lib/writefully/tools/pencil.rb
writefully-0.4.7 lib/writefully/tools/pencil.rb
writefully-0.4.6 lib/writefully/tools/pencil.rb
writefully-0.4.5 lib/writefully/tools/pencil.rb
writefully-0.4.4 lib/writefully/tools/pencil.rb
writefully-0.4.2 lib/writefully/tools/pencil.rb
writefully-0.4.1 lib/writefully/tools/pencil.rb
writefully-0.4.0 lib/writefully/tools/pencil.rb
writefully-0.3.6 lib/writefully/tools/pencil.rb