DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Get A Bible Passage From The ESV Web Service With Ruby

05.17.2006
| 3942 views |
  • submit to reddit
        
require 'net/http'

BASE_URL = 'http://www.gnpcb.org/esv/share/get/'
OPTIONS = {
  'key' => 'IP',
  'action' => 'doPassageQuery',
  'include-verse-numbers' => '0',
  'include-short-copyright' => '0',
  'output-format' => 'plain-text',
  'include-passage-horizontal-lines' => '0',
  'include-heading-horizontal-lines' => '0',
  'include-passage-references' => '1',
  'include-first-verse-numbers' => '0',
  'include-footnotes' => '0',
  'include-footnote-links' => '0',
  'include-headings' => '0',
  'include-subheadings' => '0',
  'line-length' => '0',
}

def combine_refs(refs)
  combined = refs.first
  refs[1..-1].each do |ref|
    if combined.index(ref.gsub(/\:.*$/, '')) == 0
      combined += ',' + /\:(.*)$/.match(ref)[1]
    elsif combined.index(ref.gsub(/\d+\:.*$/, '')) == 0
      combined += ';' + /\d+\:.*$/.match(ref)[0]
    else
      return nil # couldn't do it - fail *not* gracefully
    end
  end
  combined
end

def lookup_esv(reference)
  return if reference.nil? or reference.empty?
  url = BASE_URL + '?' + OPTIONS.map { |name, value| "#{name}=#{value}" }.join('&') + '&passage=' + URI.escape(reference)
  result = Net::HTTP.get(URI.parse(url))
  if result =~ /^ERROR/
    puts 'Error retrieving verse from web service'
    nil
  else
    refs = []
    result.scan(/^\S.+$/) {|ref| refs << ref }
    refs.each {|ref| result.gsub! ref, '' }
    reference = combine_refs(refs)
    text = result.gsub(/\s+/, ' ').strip
    text = text.gsub(/"/, '') if (text.count('"') == 1 and text[0..0] == '"')
    return {:reference => reference, :text => text}
  end
end

<strong>Usage:</strong>

> lookup_esv('John 3:16')
=> {:text=>"For God so loved the world, that he gave his only Son, that whoever
believes in him should not perish but have eternal life.", :reference=>"John 3:16"}