从 Ruby 块中调用预定义代码
Calling pre-defined code from within a Ruby block
我正在尝试使用 PrawnPDF 制作一个高度格式化的文档,并且想要一种方法来调用函数以在不同的地方一遍又一遍地生成一段特定的文本。我有的是这个
@pdf = Prawn::Document.new(:margin => [5, 5], :page_size => 'A4') do
text
text
<insert general text>
text
text
<insert general text>
etc etc
end
pdf.generate("output.pdf")
我要插入的一般文本是这样的:
pdf.bounding_box([column_check,pdf.cursor], :width => 250, :height => 12) do
pdf.stroke_color "894131"
pdf.stroke do
pdf.fill_color "894131"
pdf.fill_and_stroke_rounded_rectangle [pdf.cursor - 12,pdf.cursor], 288, 12, 0
pdf.fill_color 'FFFFFF'
end
pdf.pad(5) do
pdf.draw_text(prices[:manganese], :at => [4, pdf.cursor - 4], :size => 6)
end
pdf.fill_color '000000'
end
pdf.move_down 2
(我已经将生成 pdf 的方式更改为隐式)
我似乎无法从 Prawn::Document.new 块中调用函数,我该如何解决这个问题?我不太了解编程,所以我觉得有一个使用 yield 块或 proc 或我没有太多经验的东西的解决方案...
(基本上每次我调用它时我都希望能够为价格哈希调用不同的符号)
因为需要访问块范围之外的方法,所以我会使用具有显式块形式的 generate()
:
def general_text(pdf)
pdf.bounding_box(...) do
# ...
end
pdf.move_down 2
end
@pdf = Prawn::Document.generate("output.pdf", {:margin => [5, 5], :page_size => 'A4'}) do |pdf|
pdf.text
pdf.text
general_text(pdf)
pdf.text
pdf.text
general_text(pdf)
# ...
end
我自己没有检查过,但认为应该可以。
更新
要对哈希使用不同的键,请向 general_text() 方法添加另一个参数:
def general_text(pdf, key)
# ... prices[key] ...
end
@pdf = Prawn::Document.generate(...) do |pdf|
...
general_text(pdf, :manganese)
...
end
我正在尝试使用 PrawnPDF 制作一个高度格式化的文档,并且想要一种方法来调用函数以在不同的地方一遍又一遍地生成一段特定的文本。我有的是这个
@pdf = Prawn::Document.new(:margin => [5, 5], :page_size => 'A4') do
text
text
<insert general text>
text
text
<insert general text>
etc etc
end
pdf.generate("output.pdf")
我要插入的一般文本是这样的:
pdf.bounding_box([column_check,pdf.cursor], :width => 250, :height => 12) do
pdf.stroke_color "894131"
pdf.stroke do
pdf.fill_color "894131"
pdf.fill_and_stroke_rounded_rectangle [pdf.cursor - 12,pdf.cursor], 288, 12, 0
pdf.fill_color 'FFFFFF'
end
pdf.pad(5) do
pdf.draw_text(prices[:manganese], :at => [4, pdf.cursor - 4], :size => 6)
end
pdf.fill_color '000000'
end
pdf.move_down 2
(我已经将生成 pdf 的方式更改为隐式)
我似乎无法从 Prawn::Document.new 块中调用函数,我该如何解决这个问题?我不太了解编程,所以我觉得有一个使用 yield 块或 proc 或我没有太多经验的东西的解决方案...
(基本上每次我调用它时我都希望能够为价格哈希调用不同的符号)
因为需要访问块范围之外的方法,所以我会使用具有显式块形式的 generate()
:
def general_text(pdf)
pdf.bounding_box(...) do
# ...
end
pdf.move_down 2
end
@pdf = Prawn::Document.generate("output.pdf", {:margin => [5, 5], :page_size => 'A4'}) do |pdf|
pdf.text
pdf.text
general_text(pdf)
pdf.text
pdf.text
general_text(pdf)
# ...
end
我自己没有检查过,但认为应该可以。
更新 要对哈希使用不同的键,请向 general_text() 方法添加另一个参数:
def general_text(pdf, key)
# ... prices[key] ...
end
@pdf = Prawn::Document.generate(...) do |pdf|
...
general_text(pdf, :manganese)
...
end