0

I have created a class dynamically, and am trying to add methods to the class. Assume a string represents the command needing to be evaluated by this method.

    a = "puts x"

    myobject.metaclass.send(:define_method, k){|x|
         // cannot do this, obviously 
         eval(a)
    }

Thanks for the help.

Edit:

k is coming from the file also, it would be trivial to just write the classes in ruby instead of reading an alternate file format as a class, but I want to make it as simple as possible to create the templates. looks something like...

generic

do_something:
  environment1:    
    foo arg1 arg2
  environment2:
    bar arg
    baz arg

I know what the method is called and what the method needs to do. I determine the appropriate environment for each class instance at runtime, I just can't seem to dynamically add statements to the method.

1
  • Can't you just eval a method string? Commented Dec 9, 2012 at 2:18

1 Answer 1

3

You can use class_eval.

a = <<-CODE
  def foo(x)
    puts x
  end
CODE

myobject.class.class_eval a

Update

Can you do something like this?

new_method = <<-CODE
  def #{k}(*args)
    #{a}
  end
CODE

myobject.class.class_eval new_method

Assuming you have:

k = some_method
a = puts args

new_method = <<-CODE
      def #{k}(*args)
        #{a}
      end
    CODE

myobject.class.class_eval new_method
myobject.some_method 1, "foo", "bar"

Then it would output:

1
foo
bar
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks for the response. In this situation, a is non-mutable. I am parsing files created by ops guys, so I made the format have a simpler syntax. I've made it to the point where I have dynamically created the class and have an array of expressions as strings that I need to add to the respective method.
Yeah, I know that. I was wondering where it is coming from. :-) Poorly worded the question, admittedly.
Is the number of parameters to the method going to static?
No, but I've omitted that detail for simplicity, figure I should be able to resolve that part with *args or something.
removed - can't format in here, just going to expand on the initial question.
|

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.