Module: Imitation

Defined in:
lib/imitation.rb

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args, &block) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/imitation.rb', line 7

def method_missing(name, *args, &block)
  name_s   = name.to_s
  naked    = name_s.sub(/\?$/, '')
  plural   = naked.plural?
  pluraled = plural ? naked : naked.en.plural
  upcased  = pluraled.upcase

  if const_defined?(upcased)
    method = (plural and pluraled != pluraled.en.plural) ? 'subset' : 'rand' # 'carp' results rand
    module_eval <<-DEF, __FILE__, __LINE__
      def self.#{name_s}
        #{upcased}.#{method}#{'?' unless name_s == naked}
      end
    DEF
    __send__(name)
  else
    raise NameError, "#{upcased} is not defined for #{name_s}"
  end
end