How to dynamically create instance methods at runtime?

[ruby 1.8]

Suppose I have:

dummy "string" do
    puts "thing" 
end

Now this is a method call that has one line and one block as input arguments. Nice.

Now suppose I can have many similar calls (different method names, same arguments). Example:

otherdummy "string" do
    puts "thing"
end

Now, because they do the same, and they can be hundreds, I don’t want to create an instance method for each of the class that was needed. I would rather find a reasonable way to dynamically define a method at runtime based on a general rule.

Is it possible? What methods are commonly used?

thank

+5
source share
3 answers

method_missing, , , . - , - x.boo boo , method_missing boo, boo () :

class ActiveRecord::Base
  def method_missing(meth, *args, &block)
    if meth.to_s =~ /^find_by_(.+)$/
      run_find_by_method($1, *args, &block)
    else
      super # You *must* call super if you don't handle the
            # method, otherwise you'll mess up Ruby method
            # lookup.
    end
  end

  def run_find_by_method(attrs, *args, &block)
    # Make an array of attribute names
    attrs = attrs.split('_and_')

    # #transpose will zip the two arrays together like so:
    #   [[:a, :b, :c], [1, 2, 3]].transpose
    #   # => [[:a, 1], [:b, 2], [:c, 3]]
    attrs_with_args = [attrs, args].transpose

    # Hash[] will take the passed associative array and turn it
    # into a hash like so:
    #   Hash[[[:a, 2], [:b, 4]]] # => { :a => 2, :b => 4 }
    conditions = Hash[attrs_with_args]

    # #where and #all are new AREL goodness that will find all
    # records matching our conditions
    where(conditions).all
  end
end

define_method , , , method_missing. :

%w(user email food).each do |meth|
  define_method(meth) { @data[meth.to_sym] }
end
+8

, .

method_missing. , , - .

class MyClass
  def method_missing(meth, *args, &block)
    # handle the method dispatch as you want;
    # call super if you cannot resolve it
  end
end

, , . , :

class MyClass
  1.upto(1000) do |n|
    define_method :"method_#{n}" do
      puts "I am method #{n}!"
    end
  end
end

, define_method , .

+6

use define_method:

class Bar 
end

bar_obj = Bar.new

class << bar_obj
 define_method :new_dynamic_method do
  puts "content goes here"
 end
end

bar_obj.new_dynamic_method

Conclusion:

content goes here
+3
source

All Articles