Sha256: 75afb187bf51558775c99f814ee9145b951867c0ef7f867f945b32b1aab55f24

Contents?: true

Size: 1.59 KB

Versions: 15

Compression:

Stored size: 1.59 KB

Contents

module Delayed
  class PerformableMethod < Struct.new(:object, :method, :args)
    CLASS_STRING_FORMAT = /^CLASS\:([A-Z][\w\:]+)$/
    AR_STRING_FORMAT    = /^AR\:([A-Z][\w\:]+)\:(\d+)$/

    def initialize(object, method, args)
      raise NoMethodError, "undefined method `#{method}' for #{self.inspect}" unless object.respond_to?(method)

      self.object = dump(object)
      self.args   = args.map { |a| dump(a) }
      self.method = method.to_sym
    end

    def display_name
      case self.object
      when CLASS_STRING_FORMAT then "#{$1}.#{method}"
      when AR_STRING_FORMAT    then "#{$1}##{method}"
      else "Unknown##{method}"
      end
    end

    def perform
      load(object).send(method, *args.map{|a| load(a)})
    rescue ActiveRecord::RecordNotFound
      # We cannot do anything about objects which were deleted in the meantime
      true
    end

    def job_type
      class_name = case self.object
        when CLASS_STRING_FORMAT then $1.to_s
        when AR_STRING_FORMAT    then $1.to_s
        else self.object.class.to_s
      end
      "#{class_name}##{self.method.to_s}"
    end

    private

    def load(arg)
      case arg
      when CLASS_STRING_FORMAT then $1.constantize
      when AR_STRING_FORMAT    then $1.constantize.find($2)
      else arg
      end
    end

    def dump(arg)
      case arg
      when Class              then class_to_string(arg)
      when ActiveRecord::Base then ar_to_string(arg)
      else arg
      end
    end

    def ar_to_string(obj)
      "AR:#{obj.class}:#{obj.id}"
    end

    def class_to_string(obj)
      "CLASS:#{obj.name}"
    end
  end
end

Version data entries

15 entries across 15 versions & 1 rubygems

Version Path
blaxter-delayed_job-2.0.0 lib/delayed/performable_method.rb
blaxter-delayed_job-2.0.1 lib/delayed/performable_method.rb
blaxter-delayed_job-2.1.9 lib/delayed/performable_method.rb
blaxter-delayed_job-2.1.8 lib/delayed/performable_method.rb
blaxter-delayed_job-2.1.6 lib/delayed/performable_method.rb
blaxter-delayed_job-2.1.5 lib/delayed/performable_method.rb
blaxter-delayed_job-2.1.4 lib/delayed/performable_method.rb
blaxter-delayed_job-2.1.3 lib/delayed/performable_method.rb
blaxter-delayed_job-2.1.2 lib/delayed/performable_method.rb
blaxter-delayed_job-2.1.1 lib/delayed/performable_method.rb
blaxter-delayed_job-2.1.0 lib/delayed/performable_method.rb
blaxter-delayed_job-2.0.7 lib/delayed/performable_method.rb
blaxter-delayed_job-2.0.6 lib/delayed/performable_method.rb
blaxter-delayed_job-2.0.5 lib/delayed/performable_method.rb
blaxter-delayed_job-2.0.3 lib/delayed/performable_method.rb