Reputation: 9672
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.
Upvotes: 0
Views: 150
Reputation: 2860
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:
classname
constantAlso 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
Upvotes: 2