Search code examples
rubydocxcaracal

Caracal gem on ruby jump to different methods while continue writing on the document


I've been using the Caracal gem for Ruby, and I'm struggling to get it to jump between methods, while still writing to the same document. For example:

def main_method
   Caracal::Document.save "test.docx" do |docx|
      docx.p "stuff"
      docx.h1 "more stuff"
      docx.h2 "even more stuff"
            if $var == 1
            method1
            else
            method2
            end
   end
end

def method1
  docx.p "write this"
end

def method2
  docx.p "or write this instead"
end

But no, if I jump to another method, it doesn't continue writing in the document, and apparently there is no way with Caracal to open a document, position at the end, and continue writing (like Rubý's File.open('test.txt', 'a')

Anybody knows a way around this? I know I can put the "write this" directly inside the if statements, but this is just a basic example, in reality I need several ramifications as different conditions are met, so I really need to jump to different methods, or it would be a terrible mess.

Thanks community!!


Solution

  • The variable docx is only in scope within the block attached to the save method. In order for the other methods to be able to see and use this variable you will need to pass it as a parameter.

    First make the methods accept a parameter, e.g.

    def method1(docx)
      docx.p "write this"
    end
    

    then pass the actual variable as an argument when calling the method:

    #...
    if $var == 1
      method1(docx)
    else
    # etc...