1

I have successfully generated a ruby module from a compiled c++ library, but I want to add some ruby methods. For example one of the libraries returns a linked list of objects that you access via:

objects.get_first_object
objects.get_next_object

I would like to add a method so I can do

objects.each do |object| 
  ...
end

so probably something like

def to_a
  ret = Array.new
  obj = objects.get_first_object
  while obj
    ret << obj
    obj = objects.get_next_object
  end
  return ret
end

The question is not how to create the methods but how should I add them to the class?

Should I just open the classes and add the methods?
I was thinking of creating subclasses but that seems messy since there is inheritance involved, so I think if I do that I would have to re-create the inheritance?

If I decide to open the classes, what the best way to to that?

nPn
  • 16,254
  • 9
  • 35
  • 58
  • 1
    *Should I just open the classes and add the methods?* yes you can do that. – Arup Rakshit Dec 21 '13 at 04:43
  • 1
    see [Recommended approach to monkey patching a class in ruby](http://stackoverflow.com/questions/10337712/recommended-approach-to-monkey-patching-a-class-in-ruby) or more [ruby monkey patch class](https://www.google.co.in/search?client=ubuntu&channel=fs&q=ruby+monkey+patch+class&ie=utf-8&oe=utf-8&gws_rd=cr&ei=ZR61UpSkOMePrQeAo4HQDw) – Arup Rakshit Dec 21 '13 at 04:53

1 Answers1

2

Just open the class and add the method:

class SwigGeneratedClass
  def to_a
    ret = Array.new
    obj = objects.get_first_object
    while obj
      ret << obj
      obj = objects.get_next_object
    end
    return ret
  end
end

There's no reason to do anything fancier.

Linuxios
  • 34,849
  • 13
  • 91
  • 116
  • I decided to go with SwigGeneratedClass.class_eval do ... There seem to be a few case were that method was slightly better, but the above is fine in my case as well. – nPn Dec 31 '13 at 16:38
  • @nPn: just note that its not idomatic to use class_eval for this. – Linuxios Dec 31 '13 at 21:12