Report abuse

Based on map_by_method 0.7.0


			
module MapByMethod
  MAP_BY_METHOD_FORMAT = /^(map|collect|select|each|reject)(?:_by)?_(\w+[?!]?)$/

  module InstanceMethods
    alias_method :respond_to_before_map_by_method?, :respond_to?

    def respond_to?(method)
      respond_to_before_map_by_method?(method) or
        !!method.to_s.match(MAP_BY_METHOD_FORMAT)
    end

    protected

    alias_method :method_missing_before_map_by_method, :method_missing

    def method_missing(method, *args, &block)
      if !respond_to_before_map_by_method?(method) and
          (matches = method.to_s.match(MAP_BY_METHOD_FORMAT))
        iterator, callmethod = matches[1..2]
        # map by multiple stuff
        result = callmethod.split('_and_').collect do |method|
          self.send(iterator) { |item| item.send method }
        end

        return result.length > 1 ? result.transpose : result.first
      else
        method_missing_before_map_by_method(method, *args, &block)
      end
    end
  end

  def self.included(base)
    super
    base.send :include, InstanceMethods
  end
end

Array.send :include, MapByMethod