class BibSync::Bibliography

Attributes

file[R]
format_hook[RW]
transform_hook[RW]

Public Class Methods

new(file = nil) click to toggle source
# File lib/bibsync/bibliography.rb, line 11
def initialize(file = nil)
  @entries = {}
  @transform_hook, @format_hook = nil, nil
  load(file)
end

Public Instance Methods

<<(entry) click to toggle source
# File lib/bibsync/bibliography.rb, line 74
def <<(entry)
  raise 'Entry has no key' if !entry.key || entry.key.empty?
  raise 'Entry is already existing' if @entries.include?(entry.key)
  entry.bibliography = self
  @entries[entry.key] = entry
  dirty!
end
[](key) click to toggle source
# File lib/bibsync/bibliography.rb, line 25
def [](key)
  @entries[key.to_s]
end
clear() click to toggle source
# File lib/bibsync/bibliography.rb, line 37
def clear
  unless @entries.empty?
    @entries.clear
    dirty!
  end
end
delete(entry) click to toggle source
# File lib/bibsync/bibliography.rb, line 29
def delete(entry)
  if @entries.include?(entry.key)
    @entries.delete(entry.key)
    entry.bibliography = nil
    dirty!
  end
end
dirty!() click to toggle source
# File lib/bibsync/bibliography.rb, line 21
def dirty!
  @dirty = true
end
dirty?() click to toggle source
# File lib/bibsync/bibliography.rb, line 17
def dirty?
  @dirty
end
load(file, check = true) click to toggle source
# File lib/bibsync/bibliography.rb, line 82
def load(file, check = true)
  parse(File.read(file)) if !check || (file && File.exists?(file))
  @file = file
  @dirty = false
end
parse(text) click to toggle source
# File lib/bibsync/bibliography.rb, line 88
def parse(text)
  until text.empty?
    case text
    when /\A(\s+|%[^\n]+\n)/
      text = $'
    else
      entry = Entry.new
      text = entry.parse(text)
      entry.key ||= "entry#{@entries.size}" # Number of entries for comment id
      self << entry
    end
  end
end
relative_path(file) click to toggle source
# File lib/bibsync/bibliography.rb, line 44
def relative_path(file)
  raise 'No filename given' unless @file
  bibpath = File.absolute_path(File.dirname(@file))
  Pathname.new(file).realpath.relative_path_from(Pathname.new(bibpath)).to_s
end
save(file = nil) click to toggle source
# File lib/bibsync/bibliography.rb, line 50
def save(file = nil)
  if file
    @file = file
    dirty!
  end

  raise 'No filename given' unless @file
  if @dirty
    @transform_hook.call(self) if @transform_hook
    tmpfile = "#{@file}.tmp"
    begin
      File.open(tmpfile, 'w') {|f| f.write(self) }
      @format_hook.call(tmpfile) if @format_hook
      File.rename(tmpfile, @file)
    ensure
      File.unlink(tmpfile) rescue nil
    end
    @dirty = false
    true
  else
    false
  end
end
to_s() click to toggle source
# File lib/bibsync/bibliography.rb, line 102
def to_s
  "% #{DateTime.now}\n% Encoding: UTF8\n\n" <<
    @entries.values.join("\n") << "\n"
end