Sha256: aa4e0a1b6c754b70099a71210d5feff2e3dcce4a7d164ee49141f6b44f9062d5

Contents?: true

Size: 1.23 KB

Versions: 1

Compression:

Stored size: 1.23 KB

Contents

require 'active_support/core_ext/class/attribute'
require 'lou/transformer/step'

module Lou
  module Transformer
    # never raise this...
    class NeverError < StandardError; end

    def self.extended(base)
      base.class_eval do
        class_attribute(:steps)
        self.steps = []
        class_attribute(:error_class)
        self.error_class = Lou::Transformer::NeverError
      end
    end

    def reverse_on(error)
      self.error_class = error
    end

    def step
      Step.new.tap do |t|
        steps << t
      end
    end

    def apply(input, total_steps = steps.count)
      applied_steps = 0
      begin
        steps.last(total_steps).each do |t|
          input = t.apply(input)
          applied_steps += 1
        end
      rescue error_class => e
        total_steps == steps.count ? reverse(input, applied_steps) : raise(e)
      end
      input
    end

    def reverse(output, total_steps = steps.count)
      reversed_steps = 0
      begin
        steps.first(total_steps).reverse_each do |t|
          output = t.reverse(output)
          reversed_steps += 1
        end
      rescue error_class => e
        total_steps == steps.count ? apply(output, reversed_steps) : raise(e)
      end
      output
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
lou-0.2.1 lib/lou/transformer.rb