Sha256: f12b9fb4e8912a71a1c313072899141b222daac41be42f4927c80da73c109d71

Contents?: true

Size: 853 Bytes

Versions: 4

Compression:

Stored size: 853 Bytes

Contents

module Slavable
  def switch(*method_names)
    options = method_names.pop

    unless options.is_a?(Hash)
      raise ArgumentError, 'Unable to detect "to" option, usage: "switch :method, :other, ..., to: :connection_name"'
    end

    method_names.each do |method|
      aliased_method, punctuation = method.to_s.sub(/([?!=])$/, ''), $1
      with_name = "#{aliased_method}_with_connection#{punctuation}"
      without_name = "#{aliased_method}_without_connection#{punctuation}"
      connection = options.with_indifferent_access.fetch(:to)

      class_eval <<-eoruby, __FILE__, __LINE__ + 1
        def #{with_name}(*args, &block)
          ::ActiveRecord::Base.within(:#{connection}) { send(:#{without_name}, *args, &block) }
        end
      eoruby

      alias_method without_name, method
      alias_method method, with_name
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
slaver-0.2.3 lib/slavable.rb
slaver-0.2.2 lib/slavable.rb
slaver-0.2.0 lib/slavable.rb
slaver-0.0.2 lib/slavable.rb