0

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.

1 Answer 1

2

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

3 Comments

Uri - Where I run into problems with that is that I need not just the defined functions in the block, but also the other pre-defined functions (e.g. def say_hello). How can I get both to work together?
try using your code, and then calling class_eval(&block) in your block
Ah, that worked! I'd tried it before, but forgot to pass in the blcok with the '&' sign, and kept getting type errors!

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.