百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
B

bibtex-ruby

> 编程语言
开源

一个用于 Ruby 的 BibTeX 库、解析器和转换器。

160 stars0 点赞1 次浏览
访问官网GitHub

工具介绍

一个用于 Ruby 的 BibTeX 库、解析器和转换器。

BibTeX-Ruby

BibTeX-Ruby is the Rubyist's swiss-army-knife for all things BibTeX. It includes a parser for all common BibTeX objects (@string, @preamble, @comment and regular entries) and a sophisticated name parser that tokenizes correctly formatted names; BibTeX-Ruby recognizes BibTeX string replacements, joins values containing multiple strings or variables, supports cross-references, and decodes common LaTeX formatting instructions to unicode; if you are in a hurry, it also allows for easy export/conversion to formats such as YAML, JSON, CiteProc/CSL, XML (BibTeXML, requires rexml), and RDF (experimental).

For a list of projects using BibTeX-Ruby, take a look at the project wiki.

Quickstart

Install and load BibTeX-Ruby in an IRB session:

$ [sudo] gem install bibtex-ruby
$ irb
>> require 'bibtex'

Open a BibTeX bibliography:

ruby
b = BibTeX.open('./ruby.bib')

Select a BibTeX entry and access individual fields:

ruby
b['pickaxe'].title
#=> "Programming Ruby 1.9: The Pragmatic Programmer's Guide"
b[:pickaxe].author.length
#=> 3
b[:pickaxe].author.to_s
#=> "Thomas, D. and Fowler, Chad and Hunt, Andy"
b[:pickaxe].author[2].first
#=> "Andy"

Query a bibliography:

ruby
b['@book'].length
#=> 3 - the number books in the bibliography
b['@article'].length
#=> 0 - the number of articles in the bibliography
b['@book[year=2009]'].length
#=> 1 - the number of books published in 2009

Extend first name initials throughout your bibliography:

ruby
b.extend_initials ['Dave', 'Thomas']
b[:pickaxe].author.to_s
#=> "Thomas, Dave and Fowler, Chad and Hunt, Andy"

You can also extend all names in the bibliography to their prototypical (i.e., the longest available) form:

ruby
b.extend_initials! #=> extends all names in the bibliography

Use with caution as this method will treat two names as identical if they look the same in their #sort_order(:initials => true) form.

Unify certain fields across the bibliography:

ruby
b.unify :publisher, /o'?reilly/i, "O'Reilly"

b.unify :publisher, /^penguin/i do |entry|
  entry.publisher = 'Penguin Books'
  entry.address = 'London'
end

This will unify various spellings of entries published by O'Reilly and Penguin.

Render your bibliography in one of many different citation styles (requires the citeproc-ruby gem):

…

Save a bibliography to a file:

ruby
b.save
#=> saves the original file
b.save_to(file)
#=> saves the bibliography in a new file

Compatibility

The BibTeX-Ruby gem has been developed and tested on Ruby 2.x, 1.9.3, and 1.8; it has been confirmed to work with JRuby, Rubinius, and REE, however, there have been repeated issues (performance mostly) with MacRuby caused by MacRuby's current StringScanner implementation.

Starting with BibTeX-Ruby version 3.0, support for Ruby versions 1.9.2 and earlier has been dropped; most features will likely continue to work, but compliance with old Rubies is not a priority going forward.

Starting with BibTex-Ruby version 7.0, only ruby versions still in "security maintenance phase" will be supported. This is, as of writing Ruby 2.7 and up.

Documentation

It is very easy to use BibTeX-Ruby. You can use the top level utility methods BibTeX.open and BibTeX.parse to open a '.bib' file or to parse a string containing BibTeX contents. By default, BibTeX-Ruby will discard all text outside of regular BibTeX elements; however, if you wish to include everything, simply add :include => [:meta_content] to your invocation of BibTeX.open or BibTeX.parse.

Once BibTeX-Ruby has parsed your '.bib' file, you can easily access individual entries. For example, if you set up your bibliography as follows:

ruby
b = BibTeX.parse  :book,
  :key => :rails,
  :address => 'Raleigh, North Carolina',
  :author => 'Ruby, Sam and Thomas, Dave, and Hansson, David Heinemeier',
  :booktitle => 'Agile Web Development with Rails',
  :edition => 'third',
  :keywords => 'ruby, rails',
  :publisher => 'The Pragmatic Bookshelf',
  :series => 'The Facets of Ruby',
  :title => 'Agile Web Development with Rails',
  :year => '2009'
})

Or programmatically:

ruby
book = BibTeX::Entry.new
book.type = :book
book.key = :mybook
bib  b['fraassen_1989b'].booktitle
#=> 

Queries

Since version 1.3 BibTeX-Ruby implements a simple query language to search Bibliographies via the Bibliography#query (or Bibliography#q) methods. Additionally, you can access individual elements or groups of elements via their index using Bibliography#[]; this accessor also exposes some of the query functionality with the exception of yielding to a block. For instance:

…

Queries offer syntactic sugar for common enumerator invocations:

ruby
bib.query(:all, '@book')
#=> same as bib.select { |b| b.has_type?(:book) }
bib.query('@book')
#=> same as above
bib.query(:first, '@book')
#=> same as bib.detect { |b| b.has_type?(:book) }
bib.query(:none, '@book')
#=> same as bib.reject { |b| b.has_type?(:book) }

You can also use queries to delete entries in your bibliography:

ruby
bib.delete(/ruby/)
#=> deletes all object that match 'ruby' in their string representation
bib.delete('@comment')
#=> strips all BibTeX comments from the bibliography

String Replacement

If your bibliography contains BibTeX @string objects, you can let BibTeX-Ruby replace the strings for you. You have access to a bibliography's strings via BibTeX::Bibliography#strings or by using a '@string' query. You can replace the string symbols of an object by calling the object's the replace method. Thus, to replace all strings defined in bibliography b you could use the following code:

ruby
b.each do |obj|
  obj.replace(b.q('@string'))
end

A shorthand version for replacing all strings in a given bibliography is the Bibliography#replace method. Similarly, you can use the Bibliography#join method to join individual strings together. For instance:

ruby
    bib = BibTeX::Bibliography.new
    bib.add BibTeX::Element.parse '@string{ foo = "foo" }'
    bib  ["Hawthorne", "Melville"]

Another useful method is Bibliography#names which returns all names in your bibliography (authors, editors, translators). For example, to quickly expand the initials of a name across your entire bibliography, you could use the following snippet:

ruby
b.names.each do |name|
  if name.sort_order =~ /^Poe, E/
    name.first = 'Edgar Allen'
  end
end

There is also a short-hand for this use case:

ruby
b.extend_initials ['Edgar Allen', 'Poe']

Alternatively, if your bibliography contains the same names in various forms (e.g., 'Poe, Edgar A.', 'Poe, E.A.', 'Poe, E. Allen') you can also set all names to their longest available form:

ruby
b.extend_initials!

Use with caution, though, as this method will treat names as identical as long as their initials are the same. That is to say, 'Poe, Eric A.' would be extend to 'Poe, Edgar Allen'.

Duplicates

Large bibliographies often contain duplicate data, i.e., duplicate entries which are not completely identical (e.g., authors or editors with first names or initials, titles using different casing, different keywords etc.). BibTex-Ruby allows you to group your bibliography by any number of fields in order to detect such duplicate entries.

ruby
b.select_duplicates_by :year, :title
#=> groups the bibliography by using the year and title field as key

b.duplicates?
#=> whether or not the bibliography contains any duplicates

For more complex requirements you can use the #group_by method directly. This methods accepts a list of arguments whose value will be used for grouping and, additionally, a block. The current digest and each individual entry will be passed to the block and the block's return value is used as the final digest.

The duplicate methods above, for example, do something like this:

ruby
group_by(:year, :title) do |digest, entry|
  digest.gsub(/\s+/, '').downcase
end

You can use this method, for example, to match entries only by their author's last name and so on and so forth.

Since version 4.1.0, BibTeX-ruby supports parsing of names spelled in the East Asian order (last name, then first name). Names contain a Chinese, Japanese or Korean letter are currently assumed to be such names. If the name is written in comma-separated manner, it is parsed in the normal way.

ruby
b = BibTeX.parse( [Flanagan, まつもと, 卜部, 長尾]

Filters

Since version 1.3.8 BibTeX-Ruby comes with a plugin framework for input filters. You can use the methods convert and convert! methods if Value, Entry and Bibliography instances to easily convert string values according to a given filter. Starting with version 1.3.9 BibTeX-Ruby includes a LaTeX filter that depends on the latex-decode gem. Example:

ruby
faust = '@book{faust, title = {Faust: Der Trag\"odie Erster Teil}}'
BibTeX.parse(faust).convert(:latex)[:faust].title
#=> "Faust: Der Tragödie Erster Teil"

Conditional conversions are also supported:

ruby
faust1 = '@book{faust1, title = {Faust: Der Trag\"odie Erster Teil}}'
faust2 = '@book{faust2, title = {Faust: Der Trag\"odie Zweiter Teil}}'
p BibTeX.parse(faust1 + faust2).convert(:latex) { |e| e.key == :faust2 }.to_s

Returns:

bibtex
@book{faust1,
  title = {Faust: Der Trag\"odie Erster Teil}
}
@book{faust2,
  title = {Faust: Der Tragödie Zweiter Teil}
}

If you need to express a condition on the basis of individual fields, use the conversion methods of BibTeX::Entry with a block instead (the block will be passed the key and value of each field prior to conversion).

When working with Bibliographies that contain LaTeX it is often best to apply the filter upon opening or parsing the Bibliography. You can do this, by passing the :filter option:

ruby
BibTeX.open 'references.bib', :filter => :latex

Exports

Furthermore, BibTeX-Ruby allows you to export your bibliography for processing by other tools. Currently supported formats include YAML, JSON, and XML.

Of course, you can also export your bibliography back to BibTeX; if you include `:meta_content', your export should be identical to the original '.bib' file, except for whitespace, blank lines and letter case (BibTeX-Ruby will downcase all keys).

In order to export your bibliography use #to_s, #to_yaml, #to_json, or #to_xml, respectively. For example, the following line constitutes a simple BibTeX to YAML converter:

ruby
BibTeX.open('example.bib').to_yaml

Starting with version 2.0, BibTeX-Ruby's #to_xml exports your bibliography to the BibTeXML format via rexml. By passing the option :extended => true you can make use of the BibTeXML's extended format which will return individual person elements and name tokens (provided you have successfully parsed the names of your bibliography).

ruby
BibTeX.parse( true).write($stdout, 2)
@book{pickaxe,
  Address = {Raleigh, North Carolina},
  Author = {Thomas, Dave, and Fowler, Chad, and Hunt, Andy},
  Publisher = {The Pragmatic Bookshelf},
  Title = {Programming Ruby 1.9: The Pragmatic Programmer's Guide},
  Year = {2009}
}
END

This example parse a BibTeX entry, formats it as extended BibTeXML, and writes the following XML to standard out:

xml

  
    
      Raleigh, North Carolina
      
        
          Dave
          Thomas
        
        
          Chad
          Fowler
        
        
          Andy
          Hunt
        
      
      The Pragmatic Bookshelf
      
        Programming Ruby 1.9: The Pragmatic Programmer&apos;s Guide
      
      2009
    
  

Look at the 'examples' directory for more elabora

Issues· 19 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

Ruby

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月18日
分类编程语言
定价开源

> 相关工具

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言