#!/usr/bin/env ruby
# -*- ruby -*-

# Copyright 2000, 2001 by Jim Weirich (jweirich@one.net).
# All rights reserved.

# Permission is granted for use, copying, modification, distribution,
# and distribution of modified versions of this work as long as the
# above copyright notice is included.

require 'gem/inject.rb'

module Gem

  ####################################################################
  class MethodFinder
    
    include Gem::GemUtils
    
    attr_accessor :show_private, :flat, :use_class_methods
    
    def initialize
      @show_private = false
      @use_class_methods = false
      @flat = false
    end
    
    def methods(class_name)
      klass = class_for(class_name.to_s)
      fail "klass is nil" if klass.nil?
      if @flat then
	mods = klass.ancestors.reject {|m| [Object,Kernel].member?(m) }
      else
	mods = [klass]
      end
      mods.inject([]) { |list, mod| local_methods(mod) | list }.sort
    end
    
    private # ----------------------------------------------------------
    
    def local_methods(k)
      if @use_class_methods then
	local_class_methods(k)
      else
	local_instance_methods(k)
      end
    end
    
    def local_instance_methods(k)
      result = k.instance_methods
      if @show_private then
	result |= ( k.private_instance_methods + k.protected_instance_methods )
      end
      result
    end
    
    def local_class_methods(k)
      if k.is_a?(Class) then
	k.methods - k.superclass.methods
      else
	k.methods - Kernel.methods
      end
    end
  end
  
end
