Question

I have a function which defines and returns a new class, with some pre-built methods. E.g.:

def define_class(name, options={}, &block)
  klass = Class.new(Class) do

    def say_hello
      puts "Hello!"
    end

    def say_goodbye
      puts "Adios!"
    end
  end

  parent_class.const_set(form_class, klass)
  klass
end

So, for example, this works:

define_class("testing").new.say_hello   #=> "Hello!"

But I would like to be able to pass in custom methods through a block, which would then be added to my class, like so:

define_class "testing" do
  # ... custom methods
end

Such that this would work:

klass = define_class "testing" do
  def interject
    puts "Excuse me?"
  end
end
klass.new.interject #=> "Excuse me?"

I can't figure out how to make that work though; I've tried instance_eval, class_eval, and yield, and none are producing the desired result.

Was it helpful?

Solution

Try simply:

def define_class(name, options={}, &block)
  klass = Class.new(&block)

  parent_class.const_set(form_class, klass)
  klass
end

If you want to call the block and your own block, you should use class_eval:

def define_class(name, options={}, &block)
  klass = Class.new do

    def say_hello
      puts "Hello!"
    end

    def say_goodbye
      puts "Adios!"
    end

    class_eval(&block)
  end

  parent_class.const_set(form_class, klass)
  klass
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top