File: view.rb

package info (click to toggle)
ruby-prawn 2.5.0%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 4,528 kB
  • sloc: ruby: 17,688; sh: 43; makefile: 20
file content (58 lines) | stat: -rw-r--r-- 1,747 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# frozen_string_literal: true

require 'prawn/manual_builder'

Prawn::ManualBuilder::Chapter.new do
  title 'View'

  text do
    prose <<~TEXT
      The recommended way to extend Prawn's functionality is to include the
      <code>Prawn::View</code> mixin in your own class, which will make all
      <code>Prawn::Document</code> methods available to your custom objects.

      This approach is preferred over inheriting from
      <code>Prawn::Document</code>, as your state will be kept completely
      separate from <code>Prawn::Document</code>'s, thus avoiding accidental
      method collisions.

      Note that <code>Prawn::View</code> lazily instantiates a
      <code>Prawn::Document</code> with default initialization settings, such
      as page size, layout, margins, etc.

      By defining your own <code>document</code> method you will be able to
      override those settings and initialize a <code>Prawn::Document</code> to
      your heart's content. This method will be called repeatedly by
      <code>Prawn::View</code>, so be sure to memoize the object by assigning
      it to an instance variable via the <code>||=</code> operator.
    TEXT
  end

  # rubocop: disable Lint/ConstantDefinitionInBlock
  example eval: false, standalone: true do
    class Greeter
      include Prawn::View

      def initialize(name)
        @name = name
      end

      def document
        @document ||= Prawn::Document.new(page_size: 'A4', margin: 30)
      end

      def say_hello
        font('Courier') do
          text("Hello, #{@name}!")
        end
      end
    end

    greeter = Greeter.new('Gregory')

    greeter.say_hello

    greeter.save_as('greetings.pdf')
  end
  # rubocop: enable Lint/ConstantDefinitionInBlock
end