But I really need to give the class the method (not just instances)
because I have a collection of hundreds of thousands of objects
and need them all to have the method quickly.
The problem is that I don’t know the class that needs to include the
method
until runtime!
This won’t work:
some_object.class.include(SomeModule)
-> NoMethodError: private method `include’ called for
What is the workaround to add a method to a class (known only at
runtime)?
Thanks
You have a misunderstanding here. All methods are added to classes at
runtime, since that’s the only “time” ruby has (there is no compile
time). Of course, C-extensions are excluded from this.
You can always reopen a class:
class Array
def foo; “foo!”; end
end
[].foo # => “foo!”
But I really need to give the class the method (not just instances)
because I have a collection of hundreds of thousands of objects
and need them all to have the method quickly.
The problem is that I don’t know the class that needs to include the
method
until runtime!
This won’t work:
some_object.class.include(SomeModule)
-> NoMethodError: private method `include’ called for
What is the workaround to add a method to a class (known only at
runtime)?
Thanks
You have a misunderstanding here. All methods are added to classes at
runtime, since that’s the only “time” ruby has (there is no compile
time). Of course, C-extensions are excluded from this.
You can always reopen a class:
class Array
def foo; “foo!”; end
end
[].foo # => “foo!”
Regards
Stefan
That one went off too early, The missing paragraph:
As for your problem: you can use include, e.g. via
YourClass.send(:include, ModuleName), if you have the classname as
Symbol or String, see Module#const_get.
Regards
Stefan
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.