Sha256: 3e00a8a23ad6b352a8fdd47c43034c74526f688f3de201abf36ce53fdc62f764

Contents?: true

Size: 807 Bytes

Versions: 3

Compression:

Stored size: 807 Bytes

Contents

# ActiveRecord::Base.delegate_to_algorithm
#
# Let active records delegate certain (likely non-trivial) actions to algoritms
# 
# Arguments:
#   method: a symbol for the instance method to delegate, e.g. :destroy
#   options: a hash of options including...
#      :algorithm_klass => The class of the algorithm to delegate to; if not 
#        given, 
ActiveRecord::Base.define_singleton_method(:delegate_to_algorithm) do |method, options={}|
  algorithm_klass = options[:algorithm_klass]

  if algorithm_klass.nil?
    algorithm_klass_name = "#{method.to_s.capitalize}#{self.name}"
    algorithm_klass = Kernel.const_get(algorithm_klass_name)
  end

  self.instance_eval do
    alias_method "#{method}_original".to_sym, method
    define_method method do
      algorithm_klass.call(self)
    end
  end

end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
lev-0.0.3 lib/lev/delegate_to_algorithm.rb
lev-0.0.2 lib/lev/delegate_to_algorithm.rb
lev-0.0.1 lib/lev/delegate_to_algorithm.rb