Caracal gem on ruby 跳转到不同的方法,同时继续在文档上书写
Caracal gem on ruby jump to different methods while continue writing on the document
我一直在为 Ruby 使用 Caracal gem,我正在努力让它在方法之间跳转,同时仍然写入同一个文档。例如:
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
但是不,如果我跳转到另一种方法,它不会继续在文档中写入,显然 Caracal 无法打开文档,定位到最后,然后继续写入(就像 Rubý 的 File.open('test.txt', 'a')
有人知道解决这个问题的方法吗?我知道我可以将 "write this" 直接放在 if 语句中,但这只是一个基本示例,实际上我需要几个分支,因为满足不同的条件,所以我真的需要跳转到不同的方法,否则它会搞得一团糟。
感谢社区!!
变量 docx
仅在附加到 save
方法的块内的范围内。为了让其他方法能够看到和使用此变量,您需要将其作为参数传递。
首先让方法接受一个参数,例如
def method1(docx)
docx.p "write this"
end
然后在调用方法时将实际变量作为参数传递:
#...
if $var == 1
method1(docx)
else
# etc...
我一直在为 Ruby 使用 Caracal gem,我正在努力让它在方法之间跳转,同时仍然写入同一个文档。例如:
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
但是不,如果我跳转到另一种方法,它不会继续在文档中写入,显然 Caracal 无法打开文档,定位到最后,然后继续写入(就像 Rubý 的 File.open('test.txt', 'a')
有人知道解决这个问题的方法吗?我知道我可以将 "write this" 直接放在 if 语句中,但这只是一个基本示例,实际上我需要几个分支,因为满足不同的条件,所以我真的需要跳转到不同的方法,否则它会搞得一团糟。
感谢社区!!
变量 docx
仅在附加到 save
方法的块内的范围内。为了让其他方法能够看到和使用此变量,您需要将其作为参数传递。
首先让方法接受一个参数,例如
def method1(docx)
docx.p "write this"
end
然后在调用方法时将实际变量作为参数传递:
#...
if $var == 1
method1(docx)
else
# etc...