0

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.

2
  • 1
    Define "fast". Define "many". Can you give a better example? Commented May 19, 2017 at 1:56
  • updated it to explain Commented May 19, 2017 at 2:05

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

4 Comments

Also this code expects to receive arbitrary_class as a constant, not as a string. A call should be like generator 'ArticlesController', 'save', Article. Notice that the last argument is not a string here.
awesome. I just found stackoverflow.com/questions/3163641/get-a-class-by-name-in-ruby for that anyway. Thanks Ilya
uh oh it didnt work: NoMethodError: undefined method constantize' for "ClassName":String`
constantize comes from Rails and it does not work in plain Ruby (without Rails). Are you sure you are trying in Rails environment?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.