Sha256: 305006943acd34b225b43f5b9c8da5b66ab7245437ed059a992434d9cb9dfed6

Contents?: true

Size: 1.45 KB

Versions: 1

Compression:

Stored size: 1.45 KB

Contents

require 'thread'

module ActiveRecord
  module Acts
    module ShellscriptExecutable
      def self.included(base)
        base.extend(ClassMethods)
      end

      module ClassMethods
        def acts_as_shellscript_executable(options = {})
          configuration = { method: :execute!, script: :script }
          configuration.update(options) if options.is_a?(Hash)

          class_eval <<-EOV
            def #{configuration[:method]}(&block)
              script = @@__configuration__[:script]
              answer = ''
              if @@__configuration__[:parallel]
                Thread.new do
                  __execute__(script, answer, block)
                end
                block_given? ? nil : answer
              else
                __execute__(script, answer, block)
                block_given? ? nil : answer
              end
            end
          EOV

          class_variable_set(:@@__configuration__, configuration)
          include ::ActiveRecord::Acts::ShellscriptExecutable::InstanceMethods
        end
      end

      module InstanceMethods
        private

        def __execute__(script, answer, block = nil)
          script = send script if script.is_a? Symbol
          retval = []
          script.split("\n").each do |line|
            if block
              block.call `#{line}`
            else
              retval << `#{line}`
            end
          end
          answer.replace retval.join
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
acts_as_shellscript_executable-0.0.1 lib/acts_as_shellscript_executable/active_record/acts/shellscript_executable.rb