class Bookmarks::Document

Public: Document is your main interface to the file of bookmarks (called «document»).

Constants

FIRST_PART

First part of a bookmark's file in netscape format.

LAST_PART

Last part of a bookmark's file in netscape format.

Attributes

bookmarks[R]

Public: Returns an Array of NetscapeBookmark bookmarks.

bookmarks_format[R]

Public: Returns the Symbol format of the document. Currently

there is only one format available: `:netscape`.
document[R]

Public: Returns the String document.

total[R]

Public: Returns the Integer numbers of bookmarks in the document.

Public Class Methods

new(format: :netscape) click to toggle source

Public: Init a new Document.

format - The Symbol format of the document (Optional).

Examples

# The two following calls work the same way.
Document.new
Document.new format: :netscape
# File lib/bookmarks/document.rb, line 16
def initialize format: :netscape
  @bookmarks_format = format
  @document = ""
  @bookmarks = []
  @total = 0
  @h3_tags = []
end

Public Instance Methods

build(&block) click to toggle source

Public: Build a document, ie build a file of bookmarks.

block - A block that enumerate all NetscapeBookmark to put

into the document.

Examples

# ary is an array of NetscapeBookmark.
document.build do
  ary.each {|e| e }
end

Returns the String document.

# File lib/bookmarks/document.rb, line 50
def build &block
  @document += FIRST_PART
  block.call.each do |n|
    @document += n.to_s + "\n"
    @total += 1
  end
  @document += LAST_PART
end
parse(file_path) click to toggle source

Public: Parse a file of bookmarks (netscape format). Bookmarks could then be retrieved with bookmarks.

file_path - Full String pathname of the file to parse.

Returns the String document (see also document).

# File lib/bookmarks/document.rb, line 65
def parse file_path
  File.new(file_path).readlines.each {|line| parse_a_bookmark line }
  @total = @bookmarks.size
end

Private Instance Methods

h3_tags(line) click to toggle source

Get the h3's content of a line. H3 could be use as a tag in a netscape bookmark's file.

line - String.

Returns String h3 content or empty string.

# File lib/bookmarks/document.rb, line 100
def h3_tags line
  md = /<H3.*?>(.*?)<\/H3>/.match(line)
  md ? CGI.unescapeHTML(md[1]) : ""
end
parse_a_bookmark(line) click to toggle source

Parse a single line from a bookmarks file.

line - String.

Returns nothing. TODO This should have its own parser class.

# File lib/bookmarks/document.rb, line 78
def parse_a_bookmark line
  line = line.strip
  if line =~ /^<DT><H3/
    @h3_tags << h3_tags(line)
  elsif line =~ /^<\/DL>/
    @h3_tags.pop
  elsif line =~ /<DT><A HREF="http/
    @bookmarks << NetscapeBookmark.from_string(line)
    if (not @h3_tags.empty?) && (not @bookmarks.last.nil?)
      @bookmarks.last.add_tags @h3_tags
    end
  elsif line =~ /^<DD>/
    @bookmarks.last.description = line[4..-1].chomp
  end
end