Class: Formalizer::Form

Inherits:
Object
  • Object
show all
Defined in:
lib/formalizer/form.rb

Overview

Holds a single form template and its binding

Instance Method Summary collapse

Constructor Details

#initialize(id, path_or_html) ⇒ Form

Constructor

  • id - Unique textal identifier for the form

  • path_or_html - Either a path to a template html file, or a raw html



12
13
14
15
16
17
# File 'lib/formalizer/form.rb', line 12

def initialize id, path_or_html
  validate id, path_or_html
  parse(path_or_html)
  validate_template
  @id = id
end

Instance Method Details

#export_to_htmlObject

Exports the filled form into a raw html string



64
65
66
# File 'lib/formalizer/form.rb', line 64

def export_to_html
  @html_template.to_s
end

#export_to_pdf(filename = 'pdf') ⇒ Object

Exports the filled form into a PDF file uwing Wicked PDF gem



49
50
51
52
53
54
55
56
57
58
59
# File 'lib/formalizer/form.rb', line 49

def export_to_pdf filename = 'pdf'
  # replacing html image tags with wicked_pdf tags
  html = @html_template.to_s
  @html_template.css('img').each do |image_tag|
    html.gsub!(image_tag.to_s, replace_tag(image_tag, 'src'))
  end
  @html_template.css('link').each do |rel_tag|
    html.gsub!(rel_tag.to_s, replace_tag(rel_tag, 'href'))
  end
  WickedPdf.new.pdf_from_string(html)
end

#fill(fields) ⇒ Object

Binds fields to a template

  • fields - Hash of id => FormField object. Fields that do not exist in the form will be ignored.

  • Raises an error if a required field is not present in the fields param, or if it is present but doesn’t have a value.

Raises:

  • (TypeError)


25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/formalizer/form.rb', line 25

def fill fields
  raise TypeError unless fields.is_a?(Hash)

  @html_template.css('formalizer').each do |html_field|
    field_id = html_field.attributes['id'].value
    form_field = fields[field_id.to_sym]

    # raising error if field is required but not found in fields param, otherwise skipping this field
    if form_field.nil?
      required_attribute = html_field.attributes['required']
      field_required = !required_attribute.nil? && (required_attribute.value == '' || required_attribute.value == 'true')
      raise RequiredField, "field #{field_id} is required" if field_required
      next
    end

    # field found in field params, so we don't care if it's required or not
    html_field.content = form_field.value

  end
end