lib/vcard/field.rb in vcard-0.2.16 vs lib/vcard/field.rb in vcard-0.3.0

- old
+ new

@@ -226,29 +226,39 @@ # won't be. def copy Marshal.load(Marshal.dump(self)) end - # The String encoding of the Field. The String will be wrapped to a - # maximum line width of +width+, where +0+ means no wrapping, and nil is - # to accept the default wrapping (75, recommended by RFC2425). + LF = "\n" + + # The String encoding of the Field. The String will be wrapped + # to a maximum line width of +width+, where +0+ means no + # wrapping, and omitting it is to accept the default wrapping + # (75, recommended by RFC2425). # + # The +nl+ parameter specifies the line delimiter, which is + # defaulted to LF ("\n") for historical reasons. Relevant RFC's + # all say it should be CRLF, so it is highly recommended that + # you specify "\r\n" if you care about maximizing + # interoperability and interchangeability. + # # Note: AddressBook.app 3.0.3 neither understands to unwrap lines when it # imports vCards (it treats them as raw new-line characters), nor wraps # long lines on export. This is mostly a cosmetic problem, but wrapping # can be disabled by setting width to +0+, if desired. # # FIXME - breaks round-trip encoding, need to change this to not wrap # fields that are already wrapped. - def encode(width=nil) - width = 75 unless width - l = @line - # Wrap to width, unless width is zero. - if width > 0 - l = l.gsub(/.{#{width},#{width}}/) { |m| m + "\n " } + def encode(width = 75, nl: LF) + l = @line.rstrip + if width.zero? + l + nl + elsif width <= 1 + raise ArgumentError, "#{width} is too narrow" + else + # Wrap to width + l.scan(/\A.{,#{width}}|.{1,#{width - 1}}/).join("#{nl} ") + nl end - # Make sure it's terminated with no more than a single NL. - l.gsub(/\s*\z/, "") + "\n" end alias to_s encode # The name.