Permalink
Browse files

Entries and fields

  • Loading branch information...
1 parent a72f9ee commit 217e661e3a2d84baa6fa81882ed9e055e8b6775c @nickg committed Jun 18, 2008
Showing with 111 additions and 3 deletions.
  1. +33 −0 bibtex/entry.rb
  2. +17 −0 bibtex/field.rb
  3. +42 −1 bibtex/test_entry.rb
  4. +17 −0 bibtex/test_field.rb
  5. +1 −1 bibtex/test_lexer.rb
  6. +1 −1 run_unit_tests.rb
View
@@ -2,7 +2,40 @@ module BibTeX
# A single entry in a bibliography
class Entry
+ attr_reader :type, :key
+ def initialize(type, key)
+ @type = type
+ @key = key
+ @fields = {}
+ end
+
+ def add_field(obj, value = nil)
+ if obj.kind_of? Field then
+ @fields[obj.key] = obj
+ else
+ @fields[obj] = Field.new(obj, value)
+ end
+ end
+
+ def [](key)
+ f = @fields[key]
+ if f then
+ f.value
+ else
+ raise "No field with key #{key}"
+ end
+ end
+
+ def to_s
+ fs = @fields.collect { |k, f| " #{f.to_s}" }.join ",\n"
+ "@#{@type}{#{@key},\n#{fs}\n}\n\n"
+ end
end
+ # Different types of entries
+ module EntryType
+ Book = 'book'
+ end
+
end
View
@@ -0,0 +1,17 @@
+module BibTeX
+
+ # A field within an entry E.g. author = {Foo}
+ class Field
+ attr_reader :key, :value
+
+ def initialize(key, value)
+ @key = key
+ @value = value
+ end
+
+ def to_s
+ "#{@key} = {#{@value}}"
+ end
+ end
+
+end
View
@@ -1,2 +1,43 @@
-require 'BibTeX/entry'
+require 'bibtex/entry'
require 'test/unit'
+
+class TestEntry < Test::Unit::TestCase
+ include BibTeX
+
+ def setup
+ @e = Entry.new(EntryType::Book, 'foo01')
+ end
+
+ def test_basic
+ assert_equal EntryType::Book, @e.type
+ assert_equal 'foo01', @e.key
+ end
+
+ def add_default_fields
+ @e.add_field :author, 'C. Doof'
+ @e.add_field :year, 2007
+ @e.add_field Field.new(:url, 'www.doof.me.uk')
+ end
+
+ def test_fields
+ add_default_fields
+
+ assert_equal 'C. Doof', @e[:author]
+ assert_equal 2007, @e[:year]
+ assert_equal 'www.doof.me.uk', @e[:url]
+ end
+
+ def test_to_s
+ add_default_fields
+
+ expect = <<END
+@book{foo01,
+ author = {C. Doof},
+ year = {2007},
+ url = {www.doof.me.uk}
+}
+
+END
+ assert_equal expect, @e.to_s
+ end
+end
View
@@ -0,0 +1,17 @@
+require 'bibtex/field'
+require 'test/unit'
+
+class TestField < Test::Unit::TestCase
+ include BibTeX
+
+ def test_basic
+ f = Field.new(:author, 'C. Doof')
+ assert_equal :author, f.key
+ assert_equal 'C. Doof', f.value
+ end
+
+ def test_to_s
+ f = Field.new(:author, 'C. Doof')
+ assert_equal 'author = {C. Doof}', f.to_s
+ end
+end
View
@@ -1,4 +1,4 @@
-require 'BibTeX/lexer'
+require 'bibtex/lexer'
require 'test/unit'
class TestLexer < Test::Unit::TestCase
View
@@ -6,7 +6,7 @@
require 'test/unit'
-Dir.glob('BibTeX/test_*.rb').each do |file|
+Dir.glob('bibtex/test_*.rb').each do |file|
require file
end

0 comments on commit 217e661

Please sign in to comment.