简体   繁体   中英

Generate dynamic classes and instances methods in Ruby

I would like to generate complete classes in Ruby, that extend other classes. For example, I have my function:

def generator(classname, methodname, ModelClass)
  # make the class
  # now make the instance method on the class
end

and calling it generates a class like below:

generator 'ArticlesController' 'save' 'Article'

class ArticlesController < ApplicationController
  def save 
    @generated_params = # generate params from Article
    @item = Article.new(@generated_params)
    @item.save
  end
end

except that I can make new classes based on some input.

For your case code will be like this:

def generator(classname, methodname, arbitrary_class = ArbitraryClass)
  klass = Class.new(Parent) do
    define_method(methodname) do |*args, &block|
      @generated_params = # generate params from method_arg
      @item = arbitrary_class.new(@generated_params)
      @item.save
    end
  end
  Object.const_set classname, klass
end

This code do three things:

  1. creates an anonymous class
  2. adds a method to the new class
  3. associate the new class with classname constant

Also this code does not receive a parent class for the generated class, I hope it will be easy to add. The generated method may receive any number of argument, they available through args .

Update: I will add here a way how to receive a class constant from a string for arbitrary_class :

"Article".constantize # Article

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM