Method_missing

method_missing use for creating dynamic methods.

example

example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Klass
  def method_missing(method_name, *args, &block)
    if method_name.to_s =~ /^find_by_(.+)$/
      run_find_by_method($1, *args, &block)
    else
      super
    end
  end

  def run_find_by_method(attrs, *args, &block)
    attrs = attrs.split('_and_')

    attrs_with_args = [attrs, args].transpose

    conditions = Hash[attrs_with_args]

    str = ''
    conditions.each { |key, value|
      str += "#{key} = '#{value}' and "
    }

    p "select * from tbl where #{str[0..-6]}"
  end
end

k = Klass.new
k.find_by_name("Bunlong")
k.find_by_name_and_email("Bunlong", "bunlong.van@gmail.com")