Skip to content

Commit

Permalink
refactor field parsing
Browse files Browse the repository at this point in the history
- make the parsing more straight forward
- be less destructive (keep trailing whitespace)
- empty values will now yield '' and not nil
  • Loading branch information
jkraemer committed Aug 29, 2016
1 parent 38c35c5 commit d0795cc
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 17 deletions.
32 changes: 17 additions & 15 deletions lib/pdf_forms/field.rb
Original file line number Diff line number Diff line change
Expand Up @@ -9,33 +9,35 @@ class Field
# FieldStateOption: Ja
# FieldStateOption: Off
#
# Represenation of a PDF Form Field
# Representation of a PDF Form Field
def initialize(field_description)
last_value = nil
field_description.each_line do |line|
case line
when /FieldStateOption:\s*(.*?)\s*$/
(@options ||= []) << $1
else
line.strip!
key, value = line.split(": ", 2)
if key and key.gsub!(/Field/, "")
key = key.split(/(?=[A-Z])/).map(&:downcase).join('_').split(":")[0]
line.chomp!

if line =~ /^Field([A-Za-z]+):\s+(.*)/
_, key, value = *$~

if key == 'StateOption'
(@options ||= []) << value

else
value.chomp!
last_value = value
key = key.split(/(?=[A-Z])/).map(&:downcase).join('_')
instance_variable_set("@#{key}", value)

# dynamically add in fields that we didn't anticipate in ATTRS
unless self.respond_to?(key.to_sym)
proc = Proc.new { instance_variable_get("@#{key}".to_sym) }
self.class.send(:define_method, key.to_sym, proc)
end
last_value = value
else

# pdftk returns a line that doesn't start with "Field"
# It happens when a text field has multiple lines
last_value << "\n" << line
end

else
# pdftk returns a line that doesn't start with "Field"
# It happens when a text field has multiple lines
last_value << "\n" << line
end
end
end
Expand Down
4 changes: 2 additions & 2 deletions test/field_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@ def test_init_with_choice
assert_equal 'SomeChoiceField', f.name
assert_equal ['', '010 Foo Bar', 'Another option (xyz)'], f.options

assert_equal "http://github.com foo", f.value
assert_equal nil, f.value_default
assert_equal "http://github.com foo ", f.value
assert_equal '', f.value_default
assert_equal "Left", f.justification
assert_equal "71696384", f.flags
end
Expand Down

0 comments on commit d0795cc

Please sign in to comment.