repo_name
stringlengths 6
97
| path
stringlengths 3
341
| text
stringlengths 8
1.02M
|
|---|---|---|
voc/eventkalender
|
spec/spec_helper.rb
|
<filename>spec/spec_helper.rb
# frozen_string_literal: true
# First include simplecov to track code coverage
require 'simplecov'
SimpleCov.start do
add_filter '/spec/'
end
require 'rspec'
require 'webmock/rspec'
require 'rack/test'
require 'sinatra'
require 'haml'
%w[scraper fixnum].each do |file|
require File.join(File.dirname(__FILE__), '..', 'lib', 'eventkalender', "#{file}.rb")
end
%w[event meeting conference].each do |file|
require File.join(File.dirname(__FILE__), '..', 'lib', 'eventkalender', 'event', "#{file}.rb")
end
%w[parser meetings conferences].each do |file|
require File.join(File.dirname(__FILE__), '..', 'lib', 'eventkalender', 'parser', "#{file}.rb")
end
require File.join(File.dirname(__FILE__), '..', 'webapp.rb')
RSpec.configure do |config|
config.include Rack::Test::Methods
config.run_all_when_everything_filtered = true
config.filter_run :focus
config.color = true
config.order = 'random'
# Create fake webserver to send serve all request local
config.before(:each) do
project_root = File.expand_path(__dir__)
fixtures = {
'https://c3voc.de/wiki/eventz' => 'events.htm',
'https://c3voc.de/wiki/meetingz' => 'meetings.htm'
}
fixtures.each do |url, file|
stub_request(:get, url).to_return(body: File.read("#{project_root}/fixtures/#{file}"), status: 200, headers: { 'Content-Type' => 'text/html; charset=utf-8' })
end
end
end
def app
Sinatra::Application
end
|
voc/eventkalender
|
spec/lib/eventkalender/parser/meetings_spec.rb
|
<gh_stars>1-10
# frozen_string_literal: true
require 'spec_helper'
describe Eventkalender::Parser::Meetings do
describe '#to_txt' do
it 'should return events string' do
# pending
end
end
end
|
voc/eventkalender
|
lib/eventkalender/fixnum.rb
|
<gh_stars>1-10
# frozen_string_literal: true
# This class overwrites Integer in core to adds rails like time handling
# and can be used to determine time shifts.
#
# @example
# 1.day.ago #=> 2014-05-08 23:02:46 +0200
# @example
# 23.hours.ago #=> 2014-05-08 12:12:49 +0200
class Integer
# a day in seconds
SECONDS_IN_DAY = 24 * 60 * 60
# an hour in seconds
SECONDS_IN_HOUR = 60 * 60
# a minute in seconds
SECONDS_IN_MINUTES = 60
# Converts given number into days in seconds.
#
# @example Convert two days into seconds
# 2.days #=> 172800
#
# @return [Integer] days in seconds
def days
self * SECONDS_IN_DAY
end
# Converts given number into minutes in seconds.
#
# @example Convert two minutes into seconds
# 2.minutes #=> 120
#
# @return [Integer] minutes in seconds
def minutes
self * SECONDS_IN_MINUTES
end
# Converts given number into hours in seconds.
#
# @example Convert two hours into seconds
# 2.hours #=> 7200
#
# @return [Integer] hours in seconds
def hours
self * SECONDS_IN_HOUR
end
# Rails like helper method to get a timestamp for a given period.
#
# @example Get date two days ago
# 2.days.ago #=> 2014-05-06 23:02:46 +0200
#
# @return [Time] timestamp in the past for given period
def ago
Time.now - self
end
end
|
voc/eventkalender
|
lib/eventkalender.rb
|
# frozen_string_literal: true
require_relative 'eventkalender/event/event'
require_relative 'eventkalender/event/meeting'
require_relative 'eventkalender/event/conference'
require_relative 'eventkalender/parser/parser'
require_relative 'eventkalender/parser/conferences'
require_relative 'eventkalender/parser/meetings'
require_relative 'eventkalender/scraper'
require_relative 'eventkalender/fixnum'
# Main class witch holds version number and application name.
# The real magic is done by all in sub classes.
class Eventkalender
# eventkalender version number
VERSION = '1.1.0'
# application name
NAME = 'eventkalender'
end
|
voc/eventkalender
|
lib/eventkalender/event/event.rb
|
# frozen_string_literal: true
class Eventkalender
# Represents a voc event.
#
# @!attribute [rw] start_date
# @param date [String] witch represents start date of the event
# @return [Date] event start date
# @!attribute [rw] end_date
# @param date [String] witch represents end date of the event
# @return [Date] event end date
# @!attribute [rw] name
# @return [String] event name
# @!attribute [rw] location
# @return [String] event location
# @!attribute [rw] description
# @return [String] event description, in general it's used for event url
# @!attribute [rw] short_name
# @return [String] event synonym
# @!attribute [rw] wiki_path
# @return [String] event path in voc wiki
# @!attribute [rw] streaming
# @return [String] event streaming status
# @!attribute [rw] planing_status
# @return [String] event planing status
class Event
attr_reader :start_date, :end_date
attr_accessor :name, :location
# Create new event object
#
# @param options [Hash] to create an event with.
# @option options [String] :name The event name
# @option options [String] :location The event location
# @option options [String] :start_date Events start date
# @option options [String] :end_date Events end date
# @option options [String] :description The event description
# @option options [String] :wiki_path The event path in c3voc wiki
# @option options [String] :short_name The event short name
# @option options [String] :streaming Planed event streaming status
# @option options [String] :planing_status Planed event status
def initialize(options = {})
@name = options[:name]
@location = options[:location]
self.start_date = options[:start_date]
self.end_date = options[:end_date]
end
# Setter for start_date.
#
# @example Setting events start date.
# event.start_date = "2014-05-23" #=> "2014-05-23"
#
# @param date [String] start date of a event to set
# @return [Date] converted and set start date
def start_date=(date)
@start_date = check_date_input(date)
end
# Setter for end_date.
#
# @example Setting events end date.
# event.end_date = "2014-05-23" #=> "2014-05-23"
#
# @param date [String] end date of a event to set
# @return [Date] converted and set end date
def end_date=(date)
@end_date = check_date_input(date)
end
# Check whether an event is already done or not.
#
# @return [Boolean] true or false
def past?
end_date < Date.today
end
# Check whether an event is upcoming or not.
#
# @return [Boolean] true or false
def upcoming?
start_date >= Date.today
end
# Check whether an event is now or not.
#
# @return [Boolean] true or false
def now?
start_date <= Date.today && end_date >= Date.today
end
# Return current planing status of the event.
#
# @return [Boolean] status
def idea?
@planing_status =~ /[Ii]dea/ ? true : false
end
protected
# Convert dates into real date object
#
# @param date [String] date which needs to converted
#
# @return [Date] a valid date object if everything is fine
# @return [nil] if input was not a valid date
def check_date_input(date)
Eventkalender::Parser.date(date)
end
end
end
|
voc/eventkalender
|
spec/lib/eventkalender/parser/conferences_spec.rb
|
# frozen_string_literal: true
require 'spec_helper'
describe Eventkalender::Parser::Conferences do
before(:each) do
end
after(:each) do
@parser = nil
end
describe '#events' do
# pending
end
describe '#to_txt' do
it 'should return events string' do
# pending
end
end
describe '/events.ical?meetings=yes' do
it 'should generate right ical event format' do
get '/events.ical?meetings=yes'
ical_events = last_response.body.split(/BEGIN:VEVENT/).map { |e| 'BEGIN:VEVENT' + e }
eh_mumble = ical_events.select { |e| e =~ /.*eh17-mumble.*/ }.first
maintenance_weekend = ical_events.select { |e| e =~ /.*maintenance weekend.*/ }.first
# event with start and end time defined
expect(eh_mumble).to match(/DTSTART:20170330T200000/)
expect(eh_mumble).to match(/DTEND:20170330T230000/)
# all day event with more then one day
# end_date == user_defined_end_date + 1day
expect(maintenance_weekend).to match(/DTSTART:20161119T000000/)
expect(maintenance_weekend).to match(/DTEND:20161121T000000/)
end
end
end
|
voc/eventkalender
|
spec/lib/eventkalender/fixnum_spec.rb
|
# frozen_string_literal: true
require 'spec_helper'
describe 'Integer' do
describe 'Constants' do
it 'should have seconds per day,
seconds per hour and
seconds per minutes defined' do
expect(Integer::SECONDS_IN_DAY).to eq 86_400
expect(Integer::SECONDS_IN_HOUR).to eq 3_600
expect(Integer::SECONDS_IN_MINUTES).to eq 60
end
end
describe '.ago' do
it 'should return a pased time stamp' do
expect(2.days.ago.to_s).to eq((Time.now - 172_800).to_s)
end
it 'should return Time object' do
expect(23.days.ago).to be_instance_of Time
end
end
describe '.minutes' do
it 'should return minutes in seconds' do
expect(2.minutes).to eq 120
end
it 'should return Integer object' do
expect(23.days).to be_instance_of Integer
end
end
describe '.hours' do
it 'should return hours in seconds' do
expect(2.hours).to eq 7_200
end
it 'should return Integer object' do
expect(23.days).to be_instance_of Integer
end
end
describe '.days' do
it 'should return days in seconds' do
expect(2.days).to eq 172_800
end
it 'should return Integer object' do
expect(23.days).to be_instance_of Integer
end
end
end
|
voc/eventkalender
|
lib/eventkalender/parser/meetings.rb
|
<gh_stars>1-10
# frozen_string_literal: true
class Eventkalender
class Parser::Meetings < Eventkalender::Parser
attr_accessor :event_table
def initialize(event_table)
@event_table = event_table
parse(event_table)
end
def events(events = parse)
events
end
# Converts events array to plain text.
#
# @example Convert events to text.
# parser.to_txt(events) #=> "Hack*n*Play2 - Freiburg21.02.2014 - 23.02.2014"
#
# @param events [Array<Event>, #events] to convert to plain text
# @return [String] txt file
def to_txt(events = self.events)
# Create empty string
txt = +''
events.each do |event|
# Add event to string
txt << "#{event.name} - #{event.location}\n"\
"#{event.start_date.strftime('%d.%m.%Y %H:%M')} Uhr"\
" - #{event.end_date.strftime('%d.%m.%Y %H:%M')} Uhr"
# Adding two empty lines when current event is not the last one
txt << "\n\n" unless events.last.name == event.name
end
txt
end
# Converts string into event object.
#
# @param table_row [Nokogiri::XML::Element] that should be converted to an event
# @return [Event] event
def to_event(table_row)
# Search all cols in event row.
raw_event = table_row.search('./td')
# return nil if no dates are set
return nil if raw_event[3].text.empty? || raw_event[4].text.empty?
begin
start_date = DateTime.parse("#{self.class.date(raw_event[3].text)} #{raw_event[5].text}") # Start date time
end_date = DateTime.parse("#{self.class.date(raw_event[4].text)} #{end_time_defined?(raw_event[6].text)}") # End date time
rescue StandardError
return nil
end
# Create new ical object and return it
Eventkalender::Meeting.new.tap do |e|
# Add more information to ical object.
e.name = raw_event[0].text # Event name
e.type = raw_event[1].text # URL
e.location = raw_event[2].text # Event location
e.start_date = start_date
e.end_date = end_date
e.link = raw_event[7].text # URL
e.tags = raw_event[8].text # Tags
end
end
# Create atom feed from given events array.
#
# @example Generate rss feed for given events.
# parser.events #=> "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<feed xmlns=\"http://www.w3.org/2005/Atom\" …"
#
# @param events [Array<Event>, #events] to convert to an atom feed
# @return [RSS::Atom::Feed] created rss feed
def to_atom(events = self.events)
RSS::Maker.make('atom') do |maker|
maker.channel.author = 'eventkalender'
maker.channel.updated = Time.now.to_s
maker.channel.about = 'http://c3voc.de/'
maker.channel.link = 'http://c3voc.de/eventkalender/events.atom?meetrings=✓'
maker.channel.links.first.rel = 'self'
maker.channel.links.first.type = 'application/atom+xml'
maker.channel.title = 'VOC Meetings'
events.each do |event|
maker.items.new_item do |item|
item.updated = Time.now.to_s
item.title = event.name
item.id = "tag:c3voc.de,#{event.start_date.strftime('%Y-%m-%d_%H:%M')}:#{event.end_date.strftime('%Y-%m-%d_%H:%M')}"
item.description = "#{event.name} in #{event.location} "\
"vom #{event.start_date.strftime('%d.%m.%Y %H:%M')} Uhr "\
"bis #{event.end_date.strftime('%d.%m.%Y %H:%M')} Uhr."
item.link = 'http://c3voc.de/eventkalender'
end
end
end
end
# Create json stream from a give events array.
#
# @example Convert given events to json
# parser.to_json #=> ""{\n \"voc_meetings\": {\n …"
#
# @param events [Array<Event>, #events] to convert to json
# @return [JSON] events in json
def to_json(events = self.events)
hash = { voc_meetings: {}, voc_meetings_count: {} }
events.each do |event|
hash[:voc_meetings][event.name] = {}
hash[:voc_meetings][event.name][:name] = event.name
hash[:voc_meetings][event.name][:location] = event.location
hash[:voc_meetings][event.name][:start_date] = event.start_date
hash[:voc_meetings][event.name][:end_date] = event.end_date
hash[:voc_meetings][event.name][:description] = event.description
hash[:voc_meetings][event.name][:tags] = event.tags
end
hash[:voc_meetings_count][:all] = events.count
JSON.pretty_generate(hash)
end
def description
@link.to_s
end
# Events with no end time defined should be created as all day event.
#
# @param parsed event end time
# @return [String] end_time
def end_time_defined?(time)
if time.empty?
'24:00'
else
time
end
end
end
end
|
someoneAnyone/PageCollectionViewLayout
|
PageCollectionViewLayout.podspec
|
<gh_stars>1-10
Pod::Spec.new do |s|
s.name = "PageCollectionViewLayout"
s.version = "0.0.1"
s.summary = "A quick and dirty UICollectionFlowLayout that mimics some of the UIPageViewController."
s.description = <<-DESC
I did not like how the UIPageViewController handled data. I didn't really need a new viewcontroller for each screen so I developed a UICollectionViewLay (subclass of UICollectionFlowLayout) that would mimic the look but would allow me to preform data updates similar to that of the UITableViewContoller.
DESC
s.homepage = "https://github.com/someoneAnyone/PageCollectionViewLayout"
s.license = 'MIT'
s.author = { "Pete" => "<EMAIL>" }
s.source = { :git => "https://github.com/someoneAnyone/PageCollectionViewLayout.git", :tag => s.version }
s.social_media_url = 'https://twitter.com/peter_ina'
s.ios.deployment_target = '8.0'
s.requires_arc = true
s.source_files = 'Pod/Classes/**/*'
s.resource_bundles = {
'PageCollectionViewLayout' => ['Pod/Assets/*.png']
}
end
|
olineham/morebetter-theme
|
lib/model_patches.rb
|
<reponame>olineham/morebetter-theme<filename>lib/model_patches.rb
# Add a callback - to be executed before each request in development,
# and at startup in production - to patch existing app classes.
# Doing so in init/environment.rb wouldn't work in development, since
# classes are reloaded, but initialization is not run each time.
# See http://stackoverflow.com/questions/7072758/plugin-not-reloading-in-development-mode
#
Rails.configuration.to_prepare do
# better URLs
InfoRequest.class_eval do
after_create :create_initial_url_title
def create_initial_url_title
update_attribute(:url_title, calculate_url_title)
end
def update_url_title
write_attribute(:url_title, calculate_url_title)
end
def calculate_url_title
"#{id}-#{title.parameterize}"
end
def title=(title)
write_attribute(:title, title)
if new_record?
url_title = title.parameterize
elsif title != url_title
write_attribute(:url_title, calculate_url_title)
end
end
end
end
|
olineham/morebetter-theme
|
lib/public_body_categories_en.rb
|
<filename>lib/public_body_categories_en.rb
# The PublicBodyCategories structure works like this:
# [
# "Main category name",
# [ "tag_to_use_as_category", "Sub category title", "sentence that can describes things in this subcategory" ],
# [ "another_tag", "Second sub category title", "another descriptive sentence for things in this subcategory"],
# "Another main category name",
# [ "another_tag_2", "Another sub category title", "another descriptive sentence"]
# ])
PublicBodyCategories.add(:en, [
"Government",
[ "ministry", "Ministries", "Ministries"],
[ "minister", "Ministers", "Ministers"],
"Councils",
[ "city_council", "City Council", "City Council"],
[ "district_council", "District Council", "District Council"],
"Health Boards",
[ "dhb", "District Health Board", "District Health Board"],
"Schools",
[ "contributing_school", "Contributing schools", "Primary schools" ],
[ "primary_school", "Primary schools", "Primary schools" ],
[ "secondary_school", "Secondary schools", "Secondary schools"],
[ "composite_school", "Composite schools", "Composite schools"],
[ "private_school", "Private schools", "Private schools are not subject to the OIA. They may <i>choose</i> to answer requests made of them"],
[ "university", "University", "University"],
"Popular agencies",
[ "popular_agency", "Popular agencies", "Popular agencies"]
])
|
olineham/morebetter-theme
|
lib/config/custom-routes.rb
|
<gh_stars>0
# Here you can override or add to the pages in the core website
Alaveteli::Application.routes.draw do
# brand new controller example
#map.with_options :controller => 'general' do |general|
# general.mycontroller '/mycontroller', :action => 'mycontroller'
#end
# Additional help page example
#map.with_options :controller => 'help' do |help|
# help.help_out '/help/help_out', :action => 'help_out'
#end
end
|
livio/SmartDeviceLink-Promisekit
|
SmartDeviceLink+PromiseKit.podspec
|
<gh_stars>1-10
Pod::Spec.new do |spec|
spec.name = 'SmartDeviceLink+PromiseKit'
spec.version = '0.2'
spec.platform = :ios, '8.0'
spec.license = { :type => "New BSD", :file => "LICENSE" }
spec.summary = 'PromiseKit extensions for SmartDeviceLink'
spec.author = '<NAME>'
spec.homepage = 'https://github.com/livio/SmartDeviceLink-PromiseKit'
spec.source = { :git => 'https://github.com/livio/SmartDeviceLink-PromiseKit.git', :tag => spec.version }
spec.source_files = 'SmartDeviceLink-PromiseKit/*'
spec.requires_arc = true
spec.dependency 'PromiseKit', '~> 4.0'
spec.dependency 'SmartDeviceLink-iOS', '~> 4.3'
end
|
dexcodeinc/pdf-reader
|
lib/pdf/reader/cmap.rb
|
# coding: utf-8
################################################################################
#
# Copyright (C) 2008 <NAME> (<EMAIL>)
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
################################################################################
class PDF::Reader
# wraps a string containing a PDF CMap and provides convenience methods for
# extracting various useful information.
#
class CMap # :nodoc:
attr_reader :map
def initialize(data)
@map = {}
process_data(data)
end
def process_data(data)
mode = nil
instructions = ""
data.each_line do |l|
if l.include?("beginbfchar")
mode = :char
elsif l.include?("endbfchar")
process_bfchar_instructions(instructions)
instructions = ""
mode = nil
elsif l.include?("beginbfrange")
mode = :range
elsif l.include?("endbfrange")
process_bfrange_instructions(instructions)
instructions = ""
mode = nil
elsif mode == :char || mode == :range
instructions << l
end
end
end
def size
@map.size
end
# Convert a glyph code into one or more Codepoints.
#
# Returns an array of Fixnums.
#
def decode(c)
# TODO: implement the conversion
return c unless c.class == Fixnum
@map[c]
end
private
def build_parser(instructions)
buffer = Buffer.new(StringIO.new(instructions))
Parser.new(buffer)
end
def str_to_int(str)
return nil if str.nil? || str.size == 0
unpacked_string = if str.size == 1 # UTF-8
str.unpack("C*")
else # UTF-16
str.unpack("n*")
end
if unpacked_string.size == 1
unpacked_string
elsif unpacked_string.size == 2 && unpacked_string[0] > 0xD800 && unpacked_string[0] < 0xDBFF
# this is a Unicode UTF-16 "Surrogate Pair" see Unicode Spec. Chapter 3.7
# lets convert to a UTF-32. (the high bit is between 0xD800-0xDBFF, the
# low bit is between 0xDC00-0xDFFF) for example: U+1D44E (U+D835 U+DC4E)
[(unpacked_string[0] - 0xD800) * 0x400 + (unpacked_string[1] - 0xDC00) + 0x10000]
else
# it is a bad idea to just return the first 16 bits, as this doesn't allow
# for ligatures for example fi (U+0066 U+0069)
unpacked_string
end
end
def process_bfchar_instructions(instructions)
parser = build_parser(instructions)
find = str_to_int(parser.parse_token)
replace = str_to_int(parser.parse_token)
while find && replace
@map[find[0]] = replace
find = str_to_int(parser.parse_token)
replace = str_to_int(parser.parse_token)
end
end
def process_bfrange_instructions(instructions)
parser = build_parser(instructions)
start = parser.parse_token
finish = parser.parse_token
to = parser.parse_token
while start && finish && to
if start.kind_of?(String) && finish.kind_of?(String) && to.kind_of?(String)
bfrange_type_one(start, finish, to)
elsif start.kind_of?(String) && finish.kind_of?(String) && to.kind_of?(Array)
bfrange_type_two(start, finish, to)
else
raise "invalid bfrange section"
end
start = parser.parse_token
finish = parser.parse_token
to = parser.parse_token
end
end
def bfrange_type_one(start_code, end_code, dst)
start_code = str_to_int(start_code)[0]
end_code = str_to_int(end_code)[0]
dst = str_to_int(dst)
# add all values in the range to our mapping
(start_code..end_code).each_with_index do |val, idx|
@map[val] = dst.length == 1 ? [dst[0] + idx] : [dst[0], dst[1] + 1]
end
end
def bfrange_type_two(start_code, end_code, dst)
start_code = str_to_int(start_code)[0]
end_code = str_to_int(end_code)[0]
from_range = (start_code..end_code)
# add all values in the range to our mapping
from_range.each_with_index do |val, idx|
@map[val] = str_to_int(dst[idx])
end
end
end
end
|
dexcodeinc/pdf-reader
|
lib/pdf/reader/standard_security_handler.rb
|
# coding: utf-8
################################################################################
#
# Copyright (C) 2011 <NAME> (<EMAIL>)
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
################################################################################
require 'digest/md5'
require 'rc4'
class PDF::Reader
# class creates interface to encrypt dictionary for use in Decrypt
class StandardSecurityHandler
## 7.6.3.3 Encryption Key Algorithm (pp61)
#
# needs a document's user password to build a key for decrypting an
# encrypted PDF document
#
PassPadBytes = [ 0x28, 0xbf, 0x4e, 0x5e, 0x4e, 0x75, 0x8a, 0x41,
0x64, 0x00, 0x4e, 0x56, 0xff, 0xfa, 0x01, 0x08,
0x2e, 0x2e, 0x00, 0xb6, 0xd0, 0x68, 0x3e, 0x80,
0x2f, 0x0c, 0xa9, 0xfe, 0x64, 0x53, 0x69, 0x7a ]
attr_reader :filter, :subFilter, :version, :key_length,
:crypt_filter, :stream_filter, :string_filter, :embedded_file_filter,
:encrypt_key
attr_reader :revision, :owner_key, :user_key, :permissions, :file_id, :password
def initialize( enc, file_id, password )
@filter = enc[:Filter]
@subFilter = enc[:SubFilter]
@version = enc[:V].to_i
@key_length = enc[:Length].to_i/8
@crypt_filter = enc[:CF]
@stream_filter = enc[:StmF]
@string_filter = enc[:StrF]
@revision = enc[:R].to_i
@owner_key = enc[:O]
@user_key = enc[:U]
@permissions = enc[:P].to_i
@embedded_file_filter = enc[:EFF]
@encryptMeta = enc.has_key?(:EncryptMetadata)? enc[:EncryptMetadata].to_s == "true" : true;
@file_id = (file_id || []).first || ""
@encrypt_key = build_standard_key(password)
end
##7.6.2 General Encryption Algorithm
#
# Algorithm 1: Encryption of data using the RC4 or AES algorithms
#
# used to decrypt RC4 encrypted PDF streams (buf)
#
# buf - a string to decrypt
# ref - a PDF::Reader::Reference for the object to decrypt
#
def decrypt( buf, ref )
objKey = @encrypt_key.dup
(0..2).each { |e| objKey << (ref.id >> e*8 & 0xFF ) }
(0..1).each { |e| objKey << (ref.gen >> e*8 & 0xFF ) }
length = objKey.length < 16 ? objKey.length : 16
rc4 = RC4.new( Digest::MD5.digest(objKey)[(0...length)] )
rc4.decrypt(buf)
end
private
# Pads supplied password to 32bytes using PassPadBytes as specified on
# pp61 of spec
def pad_pass(p="")
if p.nil? || p.empty?
PassPadBytes.pack('C*')
else
p[(0...32)] + PassPadBytes[0...(32-p.length)].pack('C*')
end
end
def xor_each_byte(buf, int)
buf.each_byte.map{ |b| b^int}.pack("C*")
end
## 7.6.3.4 Password Algorithms
#
# Algorithm 7 - Authenticating the Owner Password
#
# Used to test Owner passwords
#
# if the string is a valid owner password this will return the user
# password that should be used to decrypt the document.
#
# if the supplied password is not a valid owner password for this document
# then it returns nil
#
def auth_owner_pass(pass)
md5 = Digest::MD5.digest(pad_pass(pass))
if @revision > 2 then
50.times { md5 = Digest::MD5.digest(md5) }
keyBegins = md5[(0...@key_length)]
#first itteration decrypt owner_key
out = @owner_key
#RC4 keyed with (keyBegins XOR with itteration #) to decrypt previous out
19.downto(0).each { |i| out=RC4.new(xor_each_byte(keyBegins,i)).decrypt(out) }
else
out = RC4.new( md5[(0...5)] ).decrypt( @owner_key )
end
# c) check output as user password
auth_user_pass( out )
end
# Algorithm 6 - Authenticating the User Password
#
# Used to test User passwords
#
# if the string is a valid user password this will return the user
# password that should be used to decrypt the document.
#
# if the supplied password is not a valid user password for this document
# then it returns nil
#
def auth_user_pass(pass)
keyBegins = make_file_key(pass)
if @revision > 2
#initialize out for first iteration
out = Digest::MD5.digest(PassPadBytes.pack("C*") + @file_id)
#zero doesn't matter -> so from 0-19
20.times{ |i| out=RC4.new(xor_each_byte(keyBegins, i)).decrypt(out) }
pass = @user_key[(0...16)] == out
else
pass = RC4.new(keyBegins).encrypt(PassPadBytes.pack("C*")) == @user_key
end
pass ? keyBegins : nil
end
def make_file_key( user_pass )
# a) if there's a password, pad it to 32 bytes, else, just use the padding.
@buf = pad_pass(user_pass)
# c) add owner key
@buf << @owner_key
# d) add permissions 1 byte at a time, in little-endian order
(0..24).step(8){|e| @buf << (@permissions >> e & 0xFF)}
# e) add the file ID
@buf << @file_id
# f) if revision > 4 then if encryptMetadata add 4 bytes of 0x00 else add 4 bytes of 0xFF
if @revision > 4
@buf << [ @encryptMetadata ? 0x00 : 0xFF ].pack('C')*4
end
# b) init MD5 digest + g) finish the hash
md5 = Digest::MD5.digest(@buf)
# h) spin hash 50 times
if @revision > 2
50.times {
md5 = Digest::MD5.digest(md5[(0...@key_length)])
}
end
# i) n = key_length revision > 3, n = 5 revision == 2
md5[(0...((@revision < 3) ? 5 : @key_length))]
end
def build_standard_key(pass)
encrypt_key = auth_owner_pass(pass)
encrypt_key ||= auth_user_pass(pass)
raise PDF::Reader::EncryptedPDFError, "Invalid password (#{pass})" if encrypt_key.nil?
encrypt_key
end
end
end
|
dexcodeinc/pdf-reader
|
lib/pdf/reader/abstract_strategy.rb
|
# coding: utf-8
class PDF::Reader
# DEPRECATED: this class was deprecated in version 0.11.0 and will
# eventually be removed
class AbstractStrategy # :nodoc:
def initialize(ohash, receivers, options = {})
@ohash, @options = ohash, options
if receivers.is_a?(Array)
@receivers = receivers
else
@receivers = [receivers]
end
end
private
def options
@options || {}
end
# calls the name callback method on the receiver class with params as the arguments
#
def callback (name, params=[])
@receivers.each do |receiver|
receiver.send(name, *params) if receiver.respond_to?(name)
end
end
# strings outside of page content should be in either PDFDocEncoding or UTF-16.
def decode_strings(obj)
case obj
when String then
if obj[0,2].unpack("C*").slice(0,2) == [254,255]
PDF::Reader::Encoding.new(:UTF16Encoding).to_utf8(obj[2, obj.size])
else
PDF::Reader::Encoding.new(:PDFDocEncoding).to_utf8(obj)
end
when Hash then obj.each { |key,val| obj[key] = decode_strings(val) }
when Array then obj.collect { |item| decode_strings(item) }
else
obj
end
end
def info
ohash.object(trailer[:Info])
end
def info?
info ? true : false
end
def ohash
@ohash
end
def pages
ohash.object(root[:Pages])
end
def pages?
pages ? true : false
end
def root
ohash.object(trailer[:Root])
end
def root?
root ? true : false
end
def trailer
ohash.trailer
end
end
end
|
dexcodeinc/pdf-reader
|
lib/pdf/reader/width_calculator.rb
|
# coding: utf-8
# PDF files may define fonts in a number of ways. Each approach means we must
# calculate glyph widths differently, so this set of classes conform to an
# interface that will perform the appropriate calculations.
require 'pdf/reader/width_calculator/built_in'
require 'pdf/reader/width_calculator/composite'
require 'pdf/reader/width_calculator/true_type'
require 'pdf/reader/width_calculator/type_zero'
require 'pdf/reader/width_calculator/type_one_or_three'
|
dexcodeinc/pdf-reader
|
lib/pdf/reader/font_descriptor.rb
|
<gh_stars>1-10
# coding: utf-8
require 'ttfunk'
class PDF::Reader
# Font descriptors are outlined in Section 9.8, PDF 32000-1:2008, pp 281-288
class FontDescriptor
attr_reader :font_name, :font_family, :font_stretch, :font_weight,
:font_bounding_box, :cap_height, :ascent, :descent, :leading,
:avg_width, :max_width, :missing_width, :italic_angle, :stem_v,
:x_height, :font_flags
def initialize(ohash, fd_hash)
@ascent = ohash.object(fd_hash[:Ascent]) || 0
@descent = ohash.object(fd_hash[:Descent]) || 0
@missing_width = ohash.object(fd_hash[:MissingWidth]) || 0
@font_bounding_box = ohash.object(fd_hash[:FontBBox]) || [0,0,0,0]
@avg_width = ohash.object(fd_hash[:AvgWidth]) || 0
@cap_height = ohash.object(fd_hash[:CapHeight]) || 0
@font_flags = ohash.object(fd_hash[:Flags]) || 0
@italic_angle = ohash.object(fd_hash[:ItalicAngle])
@font_name = ohash.object(fd_hash[:FontName]).to_s
@leading = ohash.object(fd_hash[:Leading]) || 0
@max_width = ohash.object(fd_hash[:MaxWidth]) || 0
@stem_v = ohash.object(fd_hash[:StemV])
@x_height = ohash.object(fd_hash[:XHeight])
@font_stretch = ohash.object(fd_hash[:FontStretch]) || :Normal
@font_weight = ohash.object(fd_hash[:FontWeight]) || 400
@font_family = ohash.object(fd_hash[:FontFamily])
# A FontDescriptor may have an embedded font program in FontFile
# (Type 1 Font Program), FontFile2 (TrueType font program), or
# FontFile3 (Other font program as defined by Subtype entry)
# Subtype entries:
# 1) Type1C: Type 1 Font Program in Compact Font Format
# 2) CIDFontType0C: Type 0 Font Program in Compact Font Format
# 3) OpenType: OpenType Font Program
# see Section 9.9, PDF 32000-1:2008, pp 288-292
@font_program_stream = ohash.object(fd_hash[:FontFile2])
#TODO handle FontFile and FontFile3
@is_ttf = true if @font_program_stream
end
def glyph_width(char_code)
if @is_ttf
if ttf_program_stream.cmap.unicode.length > 0
glyph_id = ttf_program_stream.cmap.unicode.first[char_code]
else
glyph_id = char_code
end
char_metric = ttf_program_stream.horizontal_metrics.metrics[glyph_id]
if char_metric
return char_metric.advance_width
end
end
end
# PDF states that a glyph is 1000 units wide, true type doesn't enforce
# any behavior, but uses units/em to define how wide the 'M' is (the widest letter)
def glyph_to_pdf_scale_factor
if @is_ttf
@glyph_to_pdf_sf ||= (1.0 / ttf_program_stream.header.units_per_em) * 1000.0
else
@glyph_to_pdf_sf ||= 1.0
end
@glyph_to_pdf_sf
end
private
def ttf_program_stream
@ttf_program_stream ||= TTFunk::File.new(@font_program_stream.unfiltered_data)
end
end
end
|
dexcodeinc/pdf-reader
|
spec/reader/filter/null_spec.rb
|
# coding: utf-8
require File.dirname(__FILE__) + "/../../spec_helper"
describe PDF::Reader::Filter::Null do
it "returns the data unchanged" do
filter = PDF::Reader::Filter::Null.new
expect(filter.filter("\x00")).to eql("\x00")
end
end
|
dexcodeinc/pdf-reader
|
spec/xref_spec.rb
|
# coding: utf-8
require File.dirname(__FILE__) + "/spec_helper"
# expose the xrefs hash inside the XRef class so we can ensure it's built correctly
class PDF::Reader::XRef
attr_reader :xref
end
describe PDF::Reader::XRef, "initilisation" do
context "with cairo-basic.pdf" do
it "should load all xrefs correctly from a File" do
filename = File.new(pdf_spec_file("cairo-basic"))
tbl = PDF::Reader::XRef.new(filename)
expect(tbl.xref.keys.size).to eql(15) # 1 xref table with 16 items (ignore the first)
end
it "should load all xrefs correctly from a StringIO" do
data = StringIO.new(binread(pdf_spec_file("cairo-basic")))
tbl = PDF::Reader::XRef.new(data)
expect(tbl.xref.keys.size).to eql(15) # 1 xref table with 16 items (ignore the first)
end
end
context "with cairo-unicode.pdf" do
it "should load all xrefs correctly" do
file = File.new(pdf_spec_file("cairo-unicode"))
tbl = PDF::Reader::XRef.new(file)
expect(tbl.xref.keys.size).to eql(57) # 1 xref table with 58 items (ignore the first)
end
it "should load all xrefs correctly from a StringIO" do
data = StringIO.new(binread(pdf_spec_file("cairo-unicode")))
tbl = PDF::Reader::XRef.new(data)
expect(tbl.xref.keys.size).to eql(57) # 1 xref table with 58 items (ignore the first)
end
end
context "with openoffice-2.2.pdf" do
it "should load all xrefs correctly" do
@file = File.new(pdf_spec_file("openoffice-2.2"))
@tbl = PDF::Reader::XRef.new(@file)
expect(@tbl.xref.keys.size).to eql(28) # 1 xref table with 29 items (ignore the first)
end
end
context "with pdflatex.pdf" do
it "should load all xrefs correctly" do
@file = File.new(pdf_spec_file("pdflatex"))
@tbl = PDF::Reader::XRef.new(@file)
expect(@tbl.xref.keys.size).to eql(353) # 1 xref table with 360 items (but a bunch are ignored)
end
end
context "with xref_subsecetions.pdf" do
it "should load all xrefs correctly from a PDF that has multiple xref sections with subsections and xref streams" do
@file = File.new(pdf_spec_file("xref_subsections"))
@tbl = PDF::Reader::XRef.new(@file)
expect(@tbl.xref.keys.size).to eql(539)
end
end
context "with no_trailer.pdf" do
it "should raise an error when attempting to locate the xref table" do
@file = File.new(pdf_spec_file("no_trailer"))
expect {
PDF::Reader::XRef.new(@file)
}.to raise_error(PDF::Reader::MalformedPDFError)
end
end
context "with trailer_is_not_a_dict.pdf" do
it "should raise an error when attempting to locate the xref table" do
@file = File.new(pdf_spec_file("trailer_is_not_a_dict"))
expect {
PDF::Reader::XRef.new(@file)
}.to raise_error(PDF::Reader::MalformedPDFError)
end
end
context "with cross_ref_stream.pdf" do
let!(:file) { File.new(pdf_spec_file("cross_ref_stream"))}
subject { PDF::Reader::XRef.new(file)}
it "should correctly load all object locations" do
expect(subject.xref.keys.size).to eql(327) # 1 xref stream with 344 items (ignore the 17 free objects)
end
it "should load type 1 objects references" do
expect(subject.xref[66][0]).to eql(298219)
end
it "should load type 2 objects references" do
expect(subject.xref[281][0]).to eql(PDF::Reader::Reference.new(341,0))
end
end
context "with cross_ref_stream.pdf" do
let!(:file) { File.new(pdf_spec_file("cross_ref_stream"))}
subject { PDF::Reader::XRef.new(file)}
it "should raise an error when attempting to load an invalid xref stream" do
expect do
subject.send(:load_xref_stream, {:Subject=>"\xFE\xFF"})
end.to raise_exception(PDF::Reader::MalformedPDFError)
end
end
context "with zeroed_xref_entry.pdf" do
let!(:file) { File.new(pdf_spec_file("zeroed_xref_entry"))}
subject { PDF::Reader::XRef.new(file)}
it "should ignore non-free entries in the xref stream that point to offset 0" do
expect(subject.size).to eql(6)
expect(subject.xref.keys).not_to include(7)
end
end
context "with junk_prefix.pdf" do
it "should load all xrefs correctly from a File" do
File.open(pdf_spec_file("junk_prefix")) do |file|
tbl = PDF::Reader::XRef.new(file)
expect(tbl.xref.keys.size).to eql(6) # 1 xref table with 6 items (ignore the first)
end
end
it "should load all xrefs with an offset to skip junk at the beginning of the file" do
File.open(pdf_spec_file("junk_prefix")) do |file|
tbl = PDF::Reader::XRef.new(file)
expect(tbl.xref[1][0]).to eq(36)
expect(tbl.xref[2][0]).to eq(130)
end
end
end
end
|
dexcodeinc/pdf-reader
|
lib/pdf/reader/object_stream.rb
|
<gh_stars>1-10
# coding: utf-8
class PDF::Reader
# provides a wrapper around a PDF stream object that contains other objects in it.
# This is done for added compression and is described as an "Object Stream" in the spec.
#
class ObjectStream # :nodoc:
def initialize(stream)
@dict = stream.hash
@data = stream.unfiltered_data
end
def [](objid)
if offsets[objid].nil?
nil
else
buf = PDF::Reader::Buffer.new(StringIO.new(@data), :seek => offsets[objid])
parser = PDF::Reader::Parser.new(buf)
parser.parse_token
end
end
def size
@dict[:N]
end
private
def offsets
@offsets ||= {}
return @offsets if @offsets.keys.size > 0
size.times do
@offsets[buffer.token.to_i] = first + buffer.token.to_i
end
@offsets
end
def first
@dict[:First]
end
def buffer
@buffer ||= PDF::Reader::Buffer.new(StringIO.new(@data))
end
end
end
|
dexcodeinc/pdf-reader
|
spec/reader_spec.rb
|
<reponame>dexcodeinc/pdf-reader
# coding: utf-8
require File.dirname(__FILE__) + "/spec_helper"
describe PDF::Reader do
let(:cairo_basic) { pdf_spec_file("cairo-basic")}
let(:oo3) { pdf_spec_file("oo3")}
let(:no_text_spaces) { pdf_spec_file("no_text_spaces")}
describe "open() class method" do
it "should pass a reader instance to a block" do
PDF::Reader.open(cairo_basic) do |reader|
expect(reader.pdf_version).to eql(1.4)
end
end
end
describe "pdf_version()" do
it "should return the correct pdf_version" do
expect(PDF::Reader.new(cairo_basic).pdf_version).to eql(1.4)
end
it "should return the correct pdf_version" do
expect(PDF::Reader.new(no_text_spaces).pdf_version).to eql(1.4)
end
end
describe "page_count()" do
context "with cairo-basic" do
it "should return the correct page_count" do
expect(PDF::Reader.new(cairo_basic).page_count).to eql(2)
end
end
context "with no_text_spaces" do
it "should return the correct page_count" do
expect(PDF::Reader.new(no_text_spaces).page_count).to eql(6)
end
end
context "with indirect_page_count" do
it "should return the correct page_count" do
expect(PDF::Reader.new(pdf_spec_file("indirect_page_count")).page_count).to eql(1)
end
end
end
describe "info()" do
it "should return the correct info hash from cairo-basic" do
info = PDF::Reader.new(cairo_basic).info
expect(info.size).to eql(2)
expect(info[:Creator]).to eql("cairo 1.4.6 (http://cairographics.org)")
expect(info[:Producer]).to eql("cairo 1.4.6 (http://cairographics.org)")
end
it "should return the correct info hash from no_text_spaces" do
info = PDF::Reader.new(no_text_spaces).info
expect(info.size).to eql(9)
end
it "should return the correct info hash from a file with utf-16 encoded info" do
info = PDF::Reader.new(oo3).info
expect(info.size).to eql(3)
expect(info[:Creator]).to eql "Writer"
expect(info[:Producer]).to eql "OpenOffice.org 3.2"
expect(info[:CreationDate]).to eql "D:20101113071546-06'00'"
end
if RUBY_VERSION >= "1.9.2"
it "should return an info hash with strings marked as UTF-8" do
info = PDF::Reader.new(oo3).info
expect(info[:Creator].encoding).to eql Encoding::UTF_8
expect(info[:Producer].encoding).to eql Encoding::UTF_8
expect(info[:CreationDate].encoding).to eql Encoding::UTF_8
end
end
end
describe "metadata()" do
it "should return nil metadata from cairo-basic" do
expect(PDF::Reader.new(cairo_basic).metadata).to be_nil
end
it "should return the correct metadata from no_text_spaces" do
metadata = PDF::Reader.new(no_text_spaces).metadata
expect(metadata).to be_a_kind_of(String)
expect(metadata).to include("<x:xmpmeta")
end
if RUBY_VERSION >= "1.9.2"
it "should return the metadata string marked as UTF-8" do
metadata = PDF::Reader.new(no_text_spaces).metadata
expect(metadata.encoding).to eql Encoding::UTF_8
end
end
end
describe "pages()" do
it "should return an array of pages from cairo-basic" do
pages = PDF::Reader.new(cairo_basic).pages
expect(pages).to be_a_kind_of(Array)
expect(pages.size).to eql(2)
pages.each do |page|
expect(page).to be_a_kind_of(PDF::Reader::Page)
end
end
it "should return an array of pages from no_text_spaces" do
pages = PDF::Reader.new(no_text_spaces).pages
expect(pages).to be_a_kind_of(Array)
expect(pages.size).to eql(6)
pages.each do |page|
expect(page).to be_a_kind_of(PDF::Reader::Page)
end
end
end
describe "page()" do
it "should return a single page from cairo-basic" do
expect(PDF::Reader.new(cairo_basic).page(1)).to be_a_kind_of(PDF::Reader::Page)
end
it "should return a single page from no_text_spaces" do
expect(PDF::Reader.new(no_text_spaces).page(1)).to be_a_kind_of(PDF::Reader::Page)
end
end
end
|
dexcodeinc/pdf-reader
|
lib/pdf/reader/width_calculator/type_one_or_three.rb
|
<filename>lib/pdf/reader/width_calculator/type_one_or_three.rb
# coding: utf-8
class PDF::Reader
module WidthCalculator
# Calculates the width of a glyph in a Type One or Type Three
class TypeOneOrThree
def initialize(font)
@font = font
if @font.font_descriptor
@missing_width = @font.font_descriptor.missing_width
else
@missing_width = 0
end
end
def glyph_width(code_point)
return 0 if code_point.nil? || code_point < 0
return 0 if @font.widths.nil? || @font.widths.count == 0
# in ruby a negative index is valid, and will go from the end of the array
# which is undesireable in this case.
if @font.first_char <= code_point
@font.widths.fetch(code_point - @font.first_char, @missing_width).to_f
else
@missing_width.to_f
end
end
end
end
end
|
dexcodeinc/pdf-reader
|
lib/pdf/reader/register_receiver.rb
|
# coding: utf-8
# Copyright (C) 2010 <NAME> (<EMAIL>)
class PDF::Reader
# An example receiver that just records all callbacks generated by parsing
# a PDF file.
#
# Useful for testing the contents of a file in an rspec/test-unit suite.
#
# Usage:
#
# PDF::Reader.open("somefile.pdf") do |reader|
# receiver = PDF::Reader::RegisterReceiver.new
# reader.page(1).walk(receiver)
# callback = receiver.first_occurance_of(:show_text)
# callback[:args].first.should == "Hellow World"
# end
#
class RegisterReceiver
attr_accessor :callbacks
def initialize
@callbacks = []
end
def respond_to?(meth)
true
end
def method_missing(methodname, *args)
callbacks << {:name => methodname.to_sym, :args => args}
end
# count the number of times a callback fired
def count(methodname)
callbacks.count { |cb| cb[:name] == methodname}
end
# return the details for every time the specified callback was fired
def all(methodname)
callbacks.select { |cb| cb[:name] == methodname }
end
def all_args(methodname)
all(methodname).map { |cb| cb[:args] }
end
# return the details for the first time the specified callback was fired
def first_occurance_of(methodname)
callbacks.find { |cb| cb[:name] == methodname }
end
# return the details for the final time the specified callback was fired
def final_occurance_of(methodname)
all(methodname).last
end
# return the first occurance of a particular series of callbacks
def series(*methods)
return nil if methods.empty?
indexes = (0..(callbacks.size-1))
method_indexes = (0..(methods.size-1))
match = nil
indexes.each do |idx|
count = methods.size
method_indexes.each do |midx|
count -= 1 if callbacks[idx+midx] && callbacks[idx+midx][:name] == methods[midx]
end
if count == 0
return callbacks[idx, methods.size]
end
end
nil
end
end
end
|
dexcodeinc/pdf-reader
|
spec/page_spec.rb
|
# coding: utf-8
require File.dirname(__FILE__) + "/spec_helper"
describe PDF::Reader::Page, "raw_content()" do
it "should return a string from raw_content() from cairo-basic.pdf page 1" do
@browser = PDF::Reader.new(pdf_spec_file("cairo-basic"))
@page = @browser.page(1)
expect(@page.raw_content).to be_a_kind_of(String)
end
end
describe PDF::Reader::Page, "text()" do
# only do a very basc test here. Detailed testing of text extraction is
# done by testing the PageTextReceiver class
it "should return the text content from cairo-basic.pdf page 1" do
@browser = PDF::Reader.new(pdf_spec_file("cairo-basic"))
@page = @browser.page(1)
expect(@page.text).to eql("Hello James")
end
end
describe PDF::Reader::Page, "walk()" do
context "with page 1 of cairo-basic.pdf" do
let!(:browser) { PDF::Reader.new(pdf_spec_file("cairo-basic")) }
let!(:page) { browser.page(1) }
it "should call the special page= callback while walking content stream" do
receiver = PDF::Reader::RegisterReceiver.new
page.walk(receiver)
callbacks = receiver.callbacks.map { |cb| cb[:name] }
expect(callbacks.first).to eql(:page=)
end
it "should run callbacks while walking content stream" do
receiver = PDF::Reader::RegisterReceiver.new
page.walk(receiver)
callbacks = receiver.callbacks.map { |cb| cb[:name] }
expect(callbacks.size).to eql(16)
expect(callbacks[0]).to eql(:page=)
expect(callbacks[1]).to eql(:save_graphics_state)
end
it "should run callbacks on multiple receivers while walking content stream" do
receiver_one = PDF::Reader::RegisterReceiver.new
receiver_two = PDF::Reader::RegisterReceiver.new
page.walk(receiver_one, receiver_two)
callbacks = receiver_one.callbacks.map { |cb| cb[:name] }
expect(callbacks.size).to eql(16)
expect(callbacks.first).to eql(:page=)
callbacks = receiver_two.callbacks.map { |cb| cb[:name] }
expect(callbacks.size).to eql(16)
expect(callbacks.first).to eql(:page=)
end
end
end
describe PDF::Reader::Page, "number()" do
it "should return the text content from cairo-basic.pdf page 1" do
@browser = PDF::Reader.new(pdf_spec_file("cairo-basic"))
@page = @browser.page(1)
expect(@page.number).to eql(1)
end
end
describe PDF::Reader::Page, "number()" do
it "should return the text content from cairo-basic.pdf page 1" do
@browser = PDF::Reader.new(pdf_spec_file("cairo-basic"))
@page = @browser.page(1)
expect(@page.number).to eql(1)
end
end
describe PDF::Reader::Page, "attributes()" do
it "should contain attributes from the Page object" do
@browser = PDF::Reader.new(pdf_spec_file("inherited_page_attributes"))
@page = @browser.page(1)
attribs = @page.attributes
expect(attribs[:Resources]).to be_a_kind_of(Hash)
expect(attribs[:Resources].size).to eql(2)
end
it "should contain inherited attributes" do
@browser = PDF::Reader.new(pdf_spec_file("inherited_page_attributes"))
@page = @browser.page(1)
attribs = @page.attributes
expect(attribs[:MediaBox]).to eql([0.0, 0.0, 595.276, 841.89])
end
it "should allow Page to override inherited attributes" do
@browser = PDF::Reader.new(pdf_spec_file("override_inherited_attributes"))
@page = @browser.page(1)
attribs = @page.attributes
expect(attribs[:MediaBox]).to eql([0, 0, 200, 200])
end
it "should not include attributes from the Pages object that don't belong on a Page" do
@browser = PDF::Reader.new(pdf_spec_file("inherited_page_attributes"))
@page = @browser.page(1)
attribs = @page.attributes
expect(attribs[:Kids]).to be_nil
end
it "should not include attributes from the Pages object that don't belong on a Page" do
@browser = PDF::Reader.new(pdf_spec_file("inherited_trimbox"))
@page = @browser.page(1)
attribs = @page.attributes
expect(attribs[:TrimBox]).to be_nil
end
it "should always include Type => Page" do
@browser = PDF::Reader.new(pdf_spec_file("inherited_page_attributes"))
@page = @browser.page(1)
attribs = @page.attributes
expect(attribs[:Type]).to eql(:Page)
end
it 'should assume 8.5" x 11" if MediaBox is missing (matches Acrobat behaviour)' do
@browser = PDF::Reader.new(pdf_spec_file("mediabox_missing"))
@page = @browser.page(1)
attribs = @page.attributes
expect(attribs[:MediaBox]).to eql([0,0,612,792])
end
end
describe PDF::Reader::Page, "fonts()" do
it "should return a hash with the correct size from cairo-basic.pdf page 1" do
@browser = PDF::Reader.new(pdf_spec_file("cairo-basic"))
@page = @browser.page(1)
expect(@page.fonts).to be_a_kind_of(Hash)
expect(@page.fonts.size).to eql(1)
expect(@page.fonts.keys).to eql([:"CairoFont-0-0"])
end
it "should contain inherited resources" do
@browser = PDF::Reader.new(pdf_spec_file("cairo-basic"))
@page = @browser.page(1)
expect(@page.fonts).to be_a_kind_of(Hash)
expect(@page.fonts.size).to eql(1)
expect(@page.fonts.keys).to eql([:"CairoFont-0-0"])
end
end
describe PDF::Reader::Page, "color_spaces()" do
it "should return an empty hash from cairo-basic.pdf page 1" do
@browser = PDF::Reader.new(pdf_spec_file("cairo-basic"))
@page = @browser.page(1)
expect(@page.color_spaces).to be_a_kind_of(Hash)
expect(@page.color_spaces.size).to eql(0)
end
end
describe PDF::Reader::Page, "graphic_states()" do
it "should return an hash with 1 entry from cairo-basic.pdf page 1" do
@browser = PDF::Reader.new(pdf_spec_file("cairo-basic"))
@page = @browser.page(1)
expect(@page.graphic_states).to be_a_kind_of(Hash)
expect(@page.graphic_states.size).to eql(1)
end
end
describe PDF::Reader::Page, "orientation()" do
# this just checks that Page calls the PageOrientation class correctly. Extended specs
# to check the different orientations are correctly detected are over in the
# PageOrientation unit specs
it "should return the orientation of portrait.pdf page 1 as 'portrait'" do
@browser = PDF::Reader.new(pdf_spec_file("portrait"))
@page = @browser.page(1)
expect(@page.orientation).to eql("portrait")
end
end
describe PDF::Reader::Page, "patterns()" do
it "should return an empty hash from cairo-basic.pdf page 1" do
@browser = PDF::Reader.new(pdf_spec_file("cairo-basic"))
@page = @browser.page(1)
expect(@page.patterns).to be_a_kind_of(Hash)
expect(@page.patterns.size).to eql(0)
end
end
describe PDF::Reader::Page, "procedure_sets()" do
it "should return an empty array from cairo-basic.pdf page 1" do
@browser = PDF::Reader.new(pdf_spec_file("cairo-basic"))
@page = @browser.page(1)
expect(@page.procedure_sets).to be_a_kind_of(Array)
expect(@page.procedure_sets.size).to eql(0)
end
end
describe PDF::Reader::Page, "properties()" do
it "should return an empty hash from cairo-basic.pdf page 1" do
@browser = PDF::Reader.new(pdf_spec_file("cairo-basic"))
@page = @browser.page(1)
expect(@page.properties).to be_a_kind_of(Hash)
expect(@page.properties.size).to eql(0)
end
end
describe PDF::Reader::Page, "shadings()" do
it "should return an empty hash from cairo-basic.pdf page 1" do
@browser = PDF::Reader.new(pdf_spec_file("cairo-basic"))
@page = @browser.page(1)
expect(@page.shadings).to be_a_kind_of(Hash)
expect(@page.shadings.size).to eql(0)
end
end
describe PDF::Reader::Page, "xobjects()" do
it "should return an empty hash from cairo-basic.pdf page 1" do
@browser = PDF::Reader.new(pdf_spec_file("cairo-basic"))
@page = @browser.page(1)
expect(@page.xobjects).to be_a_kind_of(Hash)
expect(@page.xobjects.size).to eql(0)
end
end
|
dexcodeinc/pdf-reader
|
lib/pdf/reader/transformation_matrix.rb
|
# coding: utf-8
class PDF::Reader
# co-ordinate systems in PDF files are specified using a 3x3 matrix that looks
# something like this:
#
# [ a b 0 ]
# [ c d 0 ]
# [ e f 1 ]
#
# Because the final column never changes, we can represent each matrix using
# only 6 numbers. This is important to save CPU time, memory and GC pressure
# caused by allocating too many unnecessary objects.
class TransformationMatrix
attr_reader :a, :b, :c, :d, :e, :f
def initialize(a, b, c, d, e, f)
@a, @b, @c, @d, @e, @f = a, b, c, d, e, f
end
def inspect
"#{a}, #{b}, 0,\n#{c}, #{d}, #{0},\n#{e}, #{f}, 1"
end
def to_a
[@a,@b,0,
@c,@d,0,
@e,@f,1]
end
# multiply this matrix with another.
#
# the second matrix is represented by the 6 scalar values that are changeable
# in a PDF transformation matrix.
#
# WARNING: This mutates the current matrix to avoid allocating memory when
# we don't need too. Matrices are multiplied ALL THE FREAKING TIME
# so this is a worthwhile optimisation
#
# NOTE: When multiplying matrices, ordering matters. Double check
# the PDF spec to ensure you're multiplying things correctly.
#
# NOTE: see Section 8.3.3, PDF 32000-1:2008, pp 119
#
# NOTE: The if statements in this method are ordered to prefer optimisations
# that allocate fewer objects
#
# TODO: it might be worth adding an optimised path for vertical
# displacement to speed up processing documents that use vertical
# writing systems
#
def multiply!(a,b=nil,c=nil, d=nil,e=nil,f=nil)
if a == 1 && b == 0 && c == 0 && d == 1 && e == 0 && f == 0
# the identity matrix, no effect
self
elsif @a == 1 && @b == 0 && @c == 0 && @d == 1 && @e == 0 && @f == 0
# I'm the identity matrix, so just copy values across
@a = a
@b = b
@c = c
@d = d
@e = e
@f = f
elsif a == 1 && b == 0 && c == 0 && d == 1 && f == 0
# the other matrix is a horizontal displacement
horizontal_displacement_multiply!(e)
elsif @a == 1 && @b == 0 && @c == 0 && @d == 1 && @f == 0
# I'm a horizontal displacement
horizontal_displacement_multiply_reversed!(a,b,c,d,e,f)
elsif @a != 1 && @b == 0 && @c == 0 && @d != 1 && @e == 0 && @f == 0
# I'm a xy scale
xy_scaling_multiply_reversed!(a,b,c,d,e,f)
elsif a != 1 && b == 0 && c == 0 && d != 1 && e == 0 && f == 0
# the other matrix is an xy scale
xy_scaling_multiply!(a,b,c,d,e,f)
else
faster_multiply!(a,b,c, d,e,f)
end
self
end
# Optimised method for when the second matrix in the calculation is
# a simple horizontal displacement.
#
# Like this:
#
# [ 1 2 0 ] [ 1 0 0 ]
# [ 3 4 0 ] x [ 0 1 0 ]
# [ 5 6 1 ] [ e2 0 1 ]
#
def horizontal_displacement_multiply!(e2)
@e = @e + e2
end
private
# Optimised method for when the first matrix in the calculation is
# a simple horizontal displacement.
#
# Like this:
#
# [ 1 0 0 ] [ 1 2 0 ]
# [ 0 1 0 ] x [ 3 4 0 ]
# [ 5 0 1 ] [ 5 6 1 ]
#
def horizontal_displacement_multiply_reversed!(a2,b2,c2,d2,e2,f2)
newa = a2
newb = b2
newc = c2
newd = d2
newe = (@e * a2) + e2
newf = (@e * b2) + f2
@a, @b, @c, @d, @e, @f = newa, newb, newc, newd, newe, newf
end
# Optimised method for when the second matrix in the calculation is
# an X and Y scale
#
# Like this:
#
# [ 1 2 0 ] [ 5 0 0 ]
# [ 3 4 0 ] x [ 0 5 0 ]
# [ 5 6 1 ] [ 0 0 1 ]
#
def xy_scaling_multiply!(a2,b2,c2,d2,e2,f2)
newa = @a * a2
newb = @b * d2
newc = @c * a2
newd = @d * d2
newe = @e * a2
newf = @f * d2
@a, @b, @c, @d, @e, @f = newa, newb, newc, newd, newe, newf
end
# Optimised method for when the first matrix in the calculation is
# an X and Y scale
#
# Like this:
#
# [ 5 0 0 ] [ 1 2 0 ]
# [ 0 5 0 ] x [ 3 4 0 ]
# [ 0 0 1 ] [ 5 6 1 ]
#
def xy_scaling_multiply_reversed!(a2,b2,c2,d2,e2,f2)
newa = @a * a2
newb = @a * b2
newc = @d * c2
newd = @d * d2
newe = e2
newf = f2
@a, @b, @c, @d, @e, @f = newa, newb, newc, newd, newe, newf
end
# A general solution to multiplying two 3x3 matrixes. This is correct in all cases,
# but slower due to excessive object allocations. It's not actually used in any
# active code paths, but is here for reference. Use faster_multiply instead.
#
# Like this:
#
# [ a b 0 ] [ a b 0 ]
# [ c d 0 ] x [ c d 0 ]
# [ e f 1 ] [ e f 1 ]
#
def regular_multiply!(a2,b2,c2,d2,e2,f2)
newa = (@a * a2) + (@b * c2) + (0 * e2)
newb = (@a * b2) + (@b * d2) + (0 * f2)
newc = (@c * a2) + (@d * c2) + (0 * e2)
newd = (@c * b2) + (@d * d2) + (0 * f2)
newe = (@e * a2) + (@f * c2) + (1 * e2)
newf = (@e * b2) + (@f * d2) + (1 * f2)
@a, @b, @c, @d, @e, @f = newa, newb, newc, newd, newe, newf
end
# A general solution for multiplying two matrices when we know all values
# in the final column are fixed. This is the fallback method for when none
# of the optimised methods are applicable.
#
# Like this:
#
# [ a b 0 ] [ a b 0 ]
# [ c d 0 ] x [ c d 0 ]
# [ e f 1 ] [ e f 1 ]
#
def faster_multiply!(a2,b2,c2, d2,e2,f2)
newa = (@a * a2) + (@b * c2)
newb = (@a * b2) + (@b * d2)
newc = (@c * a2) + (@d * c2)
newd = (@c * b2) + (@d * d2)
newe = (@e * a2) + (@f * c2) + e2
newf = (@e * b2) + (@f * d2) + f2
@a, @b, @c, @d, @e, @f = newa, newb, newc, newd, newe, newf
end
end
end
|
dexcodeinc/pdf-reader
|
lib/pdf/reader/width_calculator/true_type.rb
|
<reponame>dexcodeinc/pdf-reader<filename>lib/pdf/reader/width_calculator/true_type.rb
# coding: utf-8
class PDF::Reader
module WidthCalculator
# Calculates the width of a glyph in a TrueType font
class TrueType
def initialize(font)
@font = font
if @font.font_descriptor
@missing_width = @font.font_descriptor.missing_width
else
@missing_width = 0
end
end
def glyph_width(code_point)
return 0 if code_point.nil? || code_point < 0
glyph_width_from_font(code_point) || glyph_width_from_descriptor(code_point)
end
private
#TODO convert Type3 units 1000 units => 1 text space unit
def glyph_width_from_font(code_point)
return if @font.widths.nil? || @font.widths.count == 0
# in ruby a negative index is valid, and will go from the end of the array
# which is undesireable in this case.
if @font.first_char <= code_point
@font.widths.fetch(code_point - @font.first_char, @missing_width).to_f
else
@missing_width.to_f
end
end
def glyph_width_from_descriptor(code_point)
return unless @font.font_descriptor
# true type fonts will have most of their information contained
# with-in a program inside the font descriptor, however the widths
# may not be in standard PDF glyph widths (1000 units => 1 text space unit)
# so this width will need to be scaled
w = @font.font_descriptor.glyph_width(code_point)
if w
w.to_f * @font.font_descriptor.glyph_to_pdf_scale_factor
else
nil
end
end
end
end
end
|
dexcodeinc/pdf-reader
|
spec/font_spec.rb
|
<filename>spec/font_spec.rb
# coding: utf-8
require File.dirname(__FILE__) + "/spec_helper"
describe PDF::Reader::Font do
let(:object_hash) { PDF::Reader::ObjectHash.allocate }
describe "basefont=()" do
let(:font) { PDF::Reader::Font.new(object_hash, {}) }
it "should select a sensible encoding when set to a symbol font" do
font.basefont = "Arial"
expect(font.encoding).to be_a_kind_of(PDF::Reader::Encoding)
font.basefont = "Symbol"
expect(font.encoding).to be_a_kind_of(PDF::Reader::Encoding)
font.basefont = "ZapfDingbats"
expect(font.encoding).to be_a_kind_of(PDF::Reader::Encoding)
end
it "should correctly store the font BaseFont" do
font.basefont = :Helvetica
expect(font.basefont).to eql(:Helvetica)
end
end
describe "to_utf8()" do
context "with no ToUnicode CMap" do
let(:font) { PDF::Reader::Font.new(object_hash, {}) }
it "should delegate to an Encoding object to convert strings to utf-8" do
encoding = double
font.encoding = encoding
expect(encoding).to receive(:to_utf8).with("hello")
font.to_utf8("hello")
end
it "should delegate to an Encoding object to convert arrays of strings to utf-8" do
encoding = double
font.encoding = encoding
expect(encoding).to receive(:to_utf8).with("hello")
expect(encoding).to receive(:to_utf8).with("howdy")
font.to_utf8(["hello", "howdy"])
end
it "should return the same type when to_utf8 is called with a string or array" do
expect(font.to_utf8("abc")).to be_a_kind_of(String)
expect(font.to_utf8(["abc"])).to be_a_kind_of(Array)
end
it "should convert integers to a utf-8 string" do
expect(font.to_utf8(123)).to be_a_kind_of(String)
end
it "should use an encoding of StandardEncoding if none has been specified" do
str = "abc\xA8"
expect(font.to_utf8(str)).to eql("abc\xC2\xA4")
end
end
context "with a ToUnicode CMap" do
let(:font) { PDF::Reader::Font.new(object_hash, {}) }
it "should delegate to a CMap object to convert strings to utf-8" do
cmap = double
expect(cmap).to receive(:decode).with(104).and_return(104)
expect(cmap).to receive(:decode).with(101).and_return(104)
expect(cmap).to receive(:decode).with(108).and_return(104)
expect(cmap).to receive(:decode).with(108).and_return(104)
expect(cmap).to receive(:decode).with(111).and_return(104)
font.tounicode = cmap
font.to_utf8("hello")
end
it "should not delegate to an Encoding object to convert strings to utf-8" do
encoding = double
expect(encoding).not_to receive(:to_utf8)
expect(encoding).to receive(:unpack).and_return("C*")
font.encoding = encoding
cmap = double
expect(cmap).to receive(:decode).exactly(5).times.and_return(104)
font.tounicode = cmap
font.to_utf8("hello")
end
end
end
describe "unpack()" do
context "with a WinAnsi encoded font" do
let(:raw) do
{
:Encoding => :WinAnsiEncoding,
:Type => :Font
}
end
let(:font) { PDF::Reader::Font.new(object_hash, raw) }
it "should unpack a binary string into ints" do
expect(font.unpack("\x41\x42")).to eq([65,66])
end
end
end
describe "glyph_width()" do
context "with a FirstChar of 1" do
let(:raw) do
{
:Encoding => :WinAnsiEncoding,
:Type => :Font,
:FirstChar => 1,
:Widths => [100, 200, 300, 400]
}
end
let(:font) { PDF::Reader::Font.new(object_hash, raw) }
it "should return the width for a glyph" do
expect(font.glyph_width(2)).to eq(200)
end
it "should return 0 for an unknown glyph" do
expect(font.glyph_width(10)).to eq(0)
end
end
context "with a FirstChar of 5" do
let(:raw) do
{
:Encoding => :WinAnsiEncoding,
:Type => :Font,
:FirstChar => 5,
:Widths => [100, 200, 300, 400]
}
end
let(:font) { PDF::Reader::Font.new(object_hash, raw) }
it "should return the width for a glyph" do
expect(font.glyph_width(7)).to eq(300)
end
it "should return 0 for an unknown glyph" do
expect(font.glyph_width(20)).to eq(0)
end
end
end
end
|
dexcodeinc/pdf-reader
|
lib/pdf-reader.rb
|
<reponame>dexcodeinc/pdf-reader<filename>lib/pdf-reader.rb
# coding: utf-8
require "pdf/reader"
|
dexcodeinc/pdf-reader
|
spec/object_hash_spec.rb
|
# coding: utf-8
require File.dirname(__FILE__) + "/spec_helper"
describe PDF::Reader::ObjectHash do
it "should have enumerable mixed in" do
filename = pdf_spec_file("cairo-unicode")
h = PDF::Reader::ObjectHash.new(filename)
expect(h.map { |ref, obj| obj.class }.size).to eql(57)
end
end
describe PDF::Reader::ObjectHash do
it "should correctly load a PDF from a StringIO object" do
filename = pdf_spec_file("cairo-unicode")
io = StringIO.new(binread(filename))
h = PDF::Reader::ObjectHash.new(io)
expect(h.map { |ref, obj| obj.class }.size).to eql(57)
end
it "should raise an ArgumentError if passed a non filename and non IO" do
filename = pdf_spec_file("cairo-unicode")
expect {PDF::Reader::ObjectHash.new(10)}.to raise_error(ArgumentError)
end
end
describe PDF::Reader::ObjectHash, "[] method" do
it "should return nil for any invalid hash key" do
filename = pdf_spec_file("cairo-unicode")
h = PDF::Reader::ObjectHash.new(filename)
expect(h[-1]).to be_nil
expect(h[nil]).to be_nil
expect(h["James"]).to be_nil
end
it "should return nil for any hash key that doesn't exist" do
filename = pdf_spec_file("cairo-unicode")
h = PDF::Reader::ObjectHash.new(filename)
expect(h[10000]).to be_nil
end
it "should correctly extract an int object using int or string keys" do
filename = pdf_spec_file("cairo-unicode")
h = PDF::Reader::ObjectHash.new(filename)
expect(h[3]).to eql(3649)
expect(h["3"]).to eql(3649)
expect(h["3james"]).to eql(3649)
end
it "should correctly extract an int object using PDF::Reference as a key" do
filename = pdf_spec_file("cairo-unicode")
h = PDF::Reader::ObjectHash.new(filename)
ref = PDF::Reader::Reference.new(3,0)
expect(h[ref]).to eql(3649)
end
end
describe PDF::Reader::ObjectHash, "object method" do
it "should return regular objects unchanged" do
filename = pdf_spec_file("cairo-unicode")
h = PDF::Reader::ObjectHash.new(filename)
expect(h.object(-1)).to eql(-1)
expect(h.object(nil)).to be_nil
expect(h.object("James")).to eql("James")
end
it "should translate reference objects into an extracted PDF object" do
filename = pdf_spec_file("cairo-unicode")
h = PDF::Reader::ObjectHash.new(filename)
expect(h.object(PDF::Reader::Reference.new(3,0))).to eql(3649)
end
end
describe PDF::Reader::ObjectHash, "deref! method" do
let(:hash) do
PDF::Reader::ObjectHash.new pdf_spec_file("cairo-unicode")
end
it "should return regular objects unchanged" do
expect(hash.deref!(-1)).to eql(-1)
expect(hash.deref!(nil)).to be_nil
expect(hash.deref!("James")).to eql("James")
end
it "should translate reference objects into an extracted PDF object" do
expect(hash.deref!(PDF::Reader::Reference.new(3,0))).to eq 3649
end
it "should recursively dereference references within hashes" do
font_descriptor = hash.deref! PDF::Reader::Reference.new(17, 0)
expect(font_descriptor[:FontFile3]).to be_an_instance_of \
PDF::Reader::Stream
end
it "should recursively dereference references within stream hashes" do
font_file = hash.deref! PDF::Reader::Reference.new(15, 0)
expect(font_file.hash[:Length]).to eq 2103
end
it "should recursively dereference references within arrays" do
font = hash.deref! PDF::Reader::Reference.new(19, 0)
expect(font[:DescendantFonts][0][:Subtype]).to eq :CIDFontType0
end
it "should return a new Hash, not mutate the provided Hash" do
orig_collection = {}
new_collection = hash.deref!(orig_collection)
expect(orig_collection.object_id).not_to eq(new_collection.object_id)
end
it "should return a new Array, not mutate the provided Array" do
orig_collection = []
new_collection = hash.deref!(orig_collection)
expect(orig_collection.object_id).not_to eq(new_collection.object_id)
end
end
describe PDF::Reader::ObjectHash, "fetch method" do
it "should raise IndexError for any invalid hash key when no default is provided" do
filename = pdf_spec_file("cairo-unicode")
h = PDF::Reader::ObjectHash.new(filename)
expect { h.fetch(-1) }.to raise_error(IndexError)
expect { h.fetch(nil) }.to raise_error(IndexError)
expect { h.fetch("James") }.to raise_error(IndexError)
end
it "should return default for any hash key that doesn't exist when a default is provided" do
filename = pdf_spec_file("cairo-unicode")
h = PDF::Reader::ObjectHash.new(filename)
expect(h.fetch(10000, "default")).to eql("default")
end
it "should correctly extract an int object using int or string keys" do
filename = pdf_spec_file("cairo-unicode")
h = PDF::Reader::ObjectHash.new(filename)
expect(h.fetch(3)).to eql(3649)
expect(h.fetch("3")).to eql(3649)
expect(h.fetch("3james")).to eql(3649)
end
it "should correctly extract an int object using PDF::Reader::Reference keys" do
filename = pdf_spec_file("cairo-unicode")
h = PDF::Reader::ObjectHash.new(filename)
ref = PDF::Reader::Reference.new(3,0)
expect(h.fetch(ref)).to eql(3649)
end
end
describe PDF::Reader::ObjectHash, "each method" do
it "should iterate 57 times when using cairo-unicode PDF" do
filename = pdf_spec_file("cairo-unicode")
h = PDF::Reader::ObjectHash.new(filename)
count = 0
h.each do
count += 1
end
expect(count).to eql(57)
end
it "should provide a PDF::Reader::Reference to each iteration" do
filename = pdf_spec_file("cairo-unicode")
h = PDF::Reader::ObjectHash.new(filename)
h.each do |id, obj|
expect(id).to be_a_kind_of(PDF::Reader::Reference)
expect(obj).not_to be_nil
end
end
end
describe PDF::Reader::ObjectHash, "each_key method" do
it "should iterate 57 times when using cairo-unicode PDF" do
filename = pdf_spec_file("cairo-unicode")
h = PDF::Reader::ObjectHash.new(filename)
count = 0
h.each_key do
count += 1
end
expect(count).to eql(57)
end
it "should provide a PDF::Reader::Reference to each iteration" do
filename = pdf_spec_file("cairo-unicode")
h = PDF::Reader::ObjectHash.new(filename)
h.each_key do |ref|
expect(ref).to be_a_kind_of(PDF::Reader::Reference)
end
end
end
describe PDF::Reader::ObjectHash, "each_value method" do
it "should iterate 57 times when using cairo-unicode PDF" do
filename = pdf_spec_file("cairo-unicode")
h = PDF::Reader::ObjectHash.new(filename)
count = 0
h.each_value do
count += 1
end
expect(count).to eql(57)
end
end
describe PDF::Reader::ObjectHash, "size method" do
it "should return 57 when using cairo-unicode PDF" do
filename = pdf_spec_file("cairo-unicode")
h = PDF::Reader::ObjectHash.new(filename)
expect(h.size).to eql(57)
end
end
describe PDF::Reader::ObjectHash, "empty? method" do
it "should return false when using cairo-unicode PDF" do
filename = pdf_spec_file("cairo-unicode")
h = PDF::Reader::ObjectHash.new(filename)
expect(h.empty?).to be_falsey
end
end
describe PDF::Reader::ObjectHash, "has_key? method" do
it "should return true when called with a valid ID" do
filename = pdf_spec_file("cairo-unicode")
h = PDF::Reader::ObjectHash.new(filename)
expect(h.has_key?(1)).to be_truthy
expect(h.has_key?(PDF::Reader::Reference.new(1,0))).to be_truthy
end
it "should return false when called with an invalid ID" do
filename = pdf_spec_file("cairo-unicode")
h = PDF::Reader::ObjectHash.new(filename)
expect(h.has_key?(-1)).to be_falsey
expect(h.has_key?(nil)).to be_falsey
expect(h.has_key?("James")).to be_falsey
expect(h.has_key?(PDF::Reader::Reference.new(10000,0))).to be_falsey
end
end
describe PDF::Reader::ObjectHash, "has_value? method" do
it "should return true when called with a valid object" do
filename = pdf_spec_file("cairo-unicode")
h = PDF::Reader::ObjectHash.new(filename)
expect(h.has_value?(3649)).to be_truthy
end
it "should return false when called with an invalid object" do
filename = pdf_spec_file("cairo-unicode")
h = PDF::Reader::ObjectHash.new(filename)
expect(h.has_value?(-1)).to be_falsey
expect(h.has_value?(nil)).to be_falsey
expect(h.has_value?("James")).to be_falsey
end
end
describe PDF::Reader::ObjectHash, "keys method" do
it "should return an array of keys" do
filename = pdf_spec_file("cairo-unicode")
h = PDF::Reader::ObjectHash.new(filename)
keys = h.keys
expect(keys.size).to eql(57)
keys.each { |k| expect(k).to be_a_kind_of(PDF::Reader::Reference) }
end
end
describe PDF::Reader::ObjectHash, "values method" do
it "should return an array of object" do
filename = pdf_spec_file("cairo-unicode")
h = PDF::Reader::ObjectHash.new(filename)
values = h.values
expect(values.size).to eql(57)
values.each { |v| expect(v).not_to be_nil }
end
end
describe PDF::Reader::ObjectHash, "values_at method" do
it "should return an array of object" do
filename = pdf_spec_file("cairo-unicode")
h = PDF::Reader::ObjectHash.new(filename)
ref3 = PDF::Reader::Reference.new(3,0)
ref6 = PDF::Reader::Reference.new(6,0)
expect(h.values_at(3,6)).to eql([3649,3287])
expect(h.values_at(ref3,ref6)).to eql([3649,3287])
end
end
describe PDF::Reader::ObjectHash, "to_a method" do
it "should return an array of 57 arrays" do
filename = pdf_spec_file("cairo-unicode")
h = PDF::Reader::ObjectHash.new(filename)
arr = h.to_a
expect(arr.size).to eql(57)
arr.each { |a| expect(a).to be_a_kind_of(Array) }
end
end
describe PDF::Reader::ObjectHash, "trailer method" do
it "should return the document trailer dictionary" do
filename = pdf_spec_file("cairo-unicode")
h = PDF::Reader::ObjectHash.new(filename)
expected = {:Size => 58,
:Root => PDF::Reader::Reference.new(57,0),
:Info => PDF::Reader::Reference.new(56,0)}
expect(h.trailer[:Size]).to eql(58)
expect(h.trailer[:Root]).to eql(PDF::Reader::Reference.new(57,0))
expect(h.trailer[:Info]).to eql(PDF::Reader::Reference.new(56,0))
end
end
describe PDF::Reader::ObjectHash, "pdf_version method" do
it "should return the document PDF version dictionary" do
filename = pdf_spec_file("cairo-unicode")
h = PDF::Reader::ObjectHash.new(filename)
expect(h.pdf_version).to eql(1.4)
end
end
describe PDF::Reader::ObjectHash, "page_references method" do
context "with cairo-unicode.pdf" do
it "should return an ordered array of references to page objects" do
filename = pdf_spec_file("cairo-unicode")
h = PDF::Reader::ObjectHash.new(filename)
arr = h.page_references
expect(arr.size).to eql(4)
expect(arr.map { |ref| ref.id }).to eql([4, 7, 10, 13])
end
end
context "with indirect_kids_array.pdf" do
it "should return an ordered array of references to page objects" do
filename = pdf_spec_file("indirect_kids_array")
h = PDF::Reader::ObjectHash.new(filename)
arr = h.page_references
expect(arr.size).to eql(1)
expect(arr.map { |ref| ref.id }).to eql([6])
end
end
end
|
dexcodeinc/pdf-reader
|
spec/width_calculator/built_in_spec.rb
|
<gh_stars>0
# coding: utf-8
require "spec_helper"
describe PDF::Reader::WidthCalculator::BuiltIn do
it_behaves_like "a WidthCalculator duck type" do
let!(:font) { double(:basefont => :Helvetica) }
subject { PDF::Reader::WidthCalculator::BuiltIn.new(font)}
end
end
describe PDF::Reader::WidthCalculator::BuiltIn, "#initialize" do
context "when the basefont is one of the 14 standard fonts" do
let!(:font) { double(:basefont => :Helvetica) }
it "should initialize with no errors" do
expect {
PDF::Reader::WidthCalculator::BuiltIn.new(font)
}.not_to raise_error
end
end
context "when the basefont is not one of the 14 standard fonts" do
let!(:font) { double(:basefont => :Foo) }
it "should raise an error" do
expect {
PDF::Reader::WidthCalculator::BuiltIn.new(font)
}.to raise_error(ArgumentError)
end
end
end
describe PDF::Reader::WidthCalculator::BuiltIn, "#glyph_width" do
context "With Helvetica, StandardEncoding and no Widths" do
let!(:encoding) { PDF::Reader::Encoding.new(:StandardEncoding) }
let!(:font) { double(:basefont => :Helvetica,
:subtype => :TrueType,
:encoding => encoding,
:widths => []) }
let(:width_calculator) {
PDF::Reader::WidthCalculator::BuiltIn.new(font)
}
it "should return width 0 for code point 160(non breaking space)" do
expect(width_calculator.glyph_width(160)).to eq(0)
end
it "should return width 0 for code point 157(unknown)" do
expect(width_calculator.glyph_width(157)).to eq(0)
end
end
end
|
dexcodeinc/pdf-reader
|
spec/cid_widths_spec.rb
|
<reponame>dexcodeinc/pdf-reader
# coding: utf-8
require File.dirname(__FILE__) + "/spec_helper"
describe PDF::Reader::CidWidths, "#initilize" do
context "with an empty array" do
subject { PDF::Reader::CidWidths.new(500, [])}
it "should return the default width" do
expect(subject[1]).to eq(500)
end
end
context "with an array using the first form" do
subject { PDF::Reader::CidWidths.new(500, [1, [10, 20, 30]])}
it "should return correct width for index 1" do
expect(subject[1]).to eq(10)
end
it "should return correct width for index 2" do
expect(subject[2]).to eq(20)
end
it "should return correct width for index 3" do
expect(subject[3]).to eq(30)
end
it "should return correct width for index 4" do
expect(subject[4]).to eq(500)
end
end
context "with an array using the second form" do
subject { PDF::Reader::CidWidths.new(500, [1, 3, 10])}
it "should return correct width for index 1" do
expect(subject[1]).to eq(10)
end
it "should return correct width for index 2" do
expect(subject[2]).to eq(10)
end
it "should return correct width for index 3" do
expect(subject[3]).to eq(10)
end
it "should return correct width for index 4" do
expect(subject[4]).to eq(500)
end
end
context "with an array mixing the first and second form" do
let!(:widths) {
[
1, [10, 20, 30],
4, 6, 40,
]
}
subject { PDF::Reader::CidWidths.new(500, widths)}
it "should return correct width for index 1" do
expect(subject[1]).to eq(10)
end
it "should return correct width for index 2" do
expect(subject[2]).to eq(20)
end
it "should return correct width for index 3" do
expect(subject[3]).to eq(30)
end
it "should return correct width for index 4" do
expect(subject[4]).to eq(40)
end
it "should return correct width for index 5" do
expect(subject[5]).to eq(40)
end
it "should return correct width for index 6" do
expect(subject[6]).to eq(40)
end
it "should return correct width for index 7" do
expect(subject[7]).to eq(500)
end
end
end
|
dexcodeinc/pdf-reader
|
lib/pdf/hash.rb
|
<filename>lib/pdf/hash.rb
# coding: utf-8
module PDF
# This class is deprecated, please stop using it.
class Hash < ::PDF::Reader::ObjectHash # :nodoc:
def initialize(input)
warn "DEPRECATION NOTICE: PDF::Hash has been deprecated, use PDF::Reader::ObjectHash instead"
super
end
def version
warn <<-EOS
DEPRECATION NOTICE: PDF::Hash#version has been deprecated,
use PDF::Reader::ObjectHash#pdf_version instead
EOS
pdf_version
end
end
end
|
dexcodeinc/pdf-reader
|
spec/pages_strategy_spec.rb
|
<reponame>dexcodeinc/pdf-reader
# coding: utf-8
require File.dirname(__FILE__) + "/spec_helper"
class PDF::Reader::PagesStrategy
public :content_stream
end
describe PDF::Reader::PagesStrategy do
let(:object_hash) { PDF::Reader::ObjectHash.allocate }
let(:font) { PDF::Reader::Font.new(object_hash, {}) }
context "processing instructions containing a single text block" do
it "should send the correct callbacks" do
# mock up an object that will be called with callbacks. This will test that
# the content class correctly recognises all instructions
receiver = double("receiver")
expect(receiver).to receive(:begin_text_object).once # BT
expect(receiver).to receive(:move_text_position).once # Td
expect(receiver).to receive(:set_text_font_and_size).once # Tf
expect(receiver).to receive(:set_text_rendering_mode).once # Tr
expect(receiver).to receive(:show_text).once # Tj
expect(receiver).to receive(:end_text_object).once # ET
# The instructions to test with
instructions = "BT\n 36.000 794.330 Td\n /F1 10.0 Tf\n 0 Tr\n (047174719X) Tj\n ET"
# process the instructions
content = PDF::Reader::PagesStrategy.new(nil, receiver)
content.content_stream(instructions, {:F1 => font})
end
end
it "should send the correct callbacks when processing instructions containing 2 text blocks" do
# mock up an object that will be called with callbacks. This will test that
# the content class correctly recognises all instructions
receiver = double("receiver")
expect(receiver).to receive(:begin_text_object).twice # BT
expect(receiver).to receive(:move_text_position).twice # Td
expect(receiver).to receive(:set_text_font_and_size).twice # Tf
expect(receiver).to receive(:set_text_rendering_mode).twice # Tr
expect(receiver).to receive(:show_text).twice # Tj
expect(receiver).to receive(:end_text_object).twice # ET
# The instructions to test with
instructions = "BT 36.000 794.330 Td /F1 10.0 Tf 0 Tr (047174719X) Tj ET\n BT 36.000 782.770 Td /F1 10.0 Tf 0 Tr (9780300110562) Tj ET"
# process the instructions
content = PDF::Reader::PagesStrategy.new(nil, receiver)
content.content_stream(instructions, {:F1 => font})
end
it "should send the correct callbacks when processing instructions containing an inline image" do
# mock up an object that will be called with callbacks. This will test that
# the content class correctly recognises all instructions
receiver = double("receiver")
expect(receiver).to receive(:begin_inline_image).once # BI
expect(receiver).to receive(:begin_inline_image_data).once # ID
expect(receiver).to receive(:end_inline_image).once # EI
# access a content stream with an inline image
filename = pdf_spec_file("inline_image")
io = File.new(filename, "r")
ohash = PDF::Reader::ObjectHash.new(io)
ref = PDF::Reader::Reference.new(3,0)
obj = ohash[ref]
# process the instructions
content = PDF::Reader::PagesStrategy.new(nil, receiver)
fonts = {:F9 => font,
:F8 => font,
:Fb => font}
content.content_stream(obj, fonts)
end
# test for a bug reported by <NAME> where params at the end of a stream would be
# silently dropped if their matching operator was in the next contream stream in a series
it "should send the correct callbacks when processing a PDF with content over multiple streams" do
receiver = PDF::Reader::RegisterReceiver.new
filename = pdf_spec_file("split_params_and_operator")
PDF::Reader.file(filename, receiver)
text_callbacks = receiver.all(:show_text_with_positioning)
expect(text_callbacks.size).to eql(2)
expect(text_callbacks[0][:args]).to eql([["My name is"]])
expect(text_callbacks[1][:args]).to eql([["<NAME>"]])
end
it "should send the correct callbacks when using more than one receiver" do
# mock up an object that will be called with callbacks. This will test that
# the content class correctly recognises all instructions
one = double("receiver_one")
expect(one).to receive(:move_text_position).once # Td
two = double("receiver_two")
expect(two).to receive(:move_text_position).once # Td
# The instructions to test with
instructions = "36.000 794.330 Td"
# process the instructions
content = PDF::Reader::PagesStrategy.new(nil, [one, two])
content.content_stream(instructions)
end
end
|
dexcodeinc/pdf-reader
|
spec/reference_spec.rb
|
<reponame>dexcodeinc/pdf-reader
# coding: utf-8
require File.dirname(__FILE__) + "/spec_helper"
describe PDF::Reader::Reference, "hash method" do
it "should return the same hash for 2 identical objects" do
one = PDF::Reader::Reference.new(1,0)
two = PDF::Reader::Reference.new(1,0)
expect(one.hash).to eq(two.hash)
end
end
describe PDF::Reader::Reference, "== method" do
it "should return true for the same object" do
one = PDF::Reader::Reference.new(1,0)
expect(one == one).to be_truthy
end
it "should return true for 2 identical objects" do
one = PDF::Reader::Reference.new(1,0)
two = PDF::Reader::Reference.new(1,0)
expect(one == two).to be_truthy
end
it "should return false if one object isn't a Reference" do
one = PDF::Reader::Reference.new(1,0)
expect(one == "two").to be_falsey
end
end
|
dexcodeinc/pdf-reader
|
spec/support/core_ext.rb
|
# coding: utf-8
class Array
def to_h
Hash[*self.flatten]
end
end
|
dexcodeinc/pdf-reader
|
lib/pdf/reader/filter/ascii_hex.rb
|
# coding: utf-8
#
class PDF::Reader
module Filter # :nodoc:
# implementation of the AsciiHex stream filter
class AsciiHex
def initialize(options = {})
@options = options
end
################################################################################
# Decode the specified data using the AsciiHex algorithm.
#
def filter(data)
data.chop! if data[-1,1] == ">"
data = data[1,data.size] if data[0,1] == "<"
data.gsub!(/[^A-Fa-f0-9]/,"")
data << "0" if data.size % 2 == 1
data.scan(/.{2}/).map { |s| s.hex.chr }.join("")
rescue Exception => e
# Oops, there was a problem decoding the stream
raise MalformedPDFError,
"Error occured while decoding an ASCIIHex stream (#{e.class.to_s}: #{e.to_s})"
end
end
end
end
|
dexcodeinc/pdf-reader
|
spec/reader/filter/lzw_spec.rb
|
<filename>spec/reader/filter/lzw_spec.rb
# coding: utf-8
require File.dirname(__FILE__) + "/../../spec_helper"
describe PDF::Reader::Filter::Lzw do
it "should filter a lzw stream with no predictors correctly" do
filter = PDF::Reader::Filter::Lzw.new
compressed_data = binread(File.dirname(__FILE__) + "/../../data/lzw_compressed.dat")
decompressed_data = binread(File.dirname(__FILE__) + "/../../data/lzw_decompressed.dat")
expect(filter.filter(compressed_data)).to eql(decompressed_data)
end
end
|
dexcodeinc/pdf-reader
|
spec/width_calculator/composite_spec.rb
|
# coding: utf-8
require "spec_helper"
describe PDF::Reader::WidthCalculator::Composite do
it_behaves_like "a WidthCalculator duck type" do
let!(:font) { double(:cid_default_width => 50,
:cid_widths => [10,[30,40]])
}
subject { PDF::Reader::WidthCalculator::Composite.new(font)}
end
end
describe PDF::Reader::WidthCalculator::Composite, "#glyph_width" do
context "when font#cid_default_width is defined" do
let!(:font) { double(:cid_default_width => 50,
:cid_widths => [10,[30,40]])
}
subject { PDF::Reader::WidthCalculator::Composite.new(font)}
context "when the glyph code is provided in cid_widths" do
it "should return the correct width" do
expect(subject.glyph_width(10)).to eq(30)
end
end
context "when the glyph code is equal to greater than font#first_char" do
it "should return the default width" do
expect(subject.glyph_width(9)).to eq(50)
end
end
end
end
|
dexcodeinc/pdf-reader
|
spec/parser_spec.rb
|
# coding: utf-8
require File.dirname(__FILE__) + "/spec_helper"
describe PDF::Reader::Parser do
include ParserHelper
include EncodingHelper
it "should parse a name correctly" do
expect(parse_string("/James").parse_token).to eql(:James)
expect(parse_string("/A;Name_With-Various***Characters?").parse_token).to eql(:"A;Name_With-Various***Characters?")
expect(parse_string("/1.2").parse_token).to eql(:"1.2")
expect(parse_string("/$$").parse_token).to eql(:"$$")
expect(parse_string("/@pattern").parse_token).to eql(:"@pattern")
expect(parse_string("/.notdef").parse_token).to eql(:".notdef")
expect(parse_string("/James#20Healy").parse_token).to eql(:"<NAME>")
expect(parse_string("/James#23Healy").parse_token).to eql(:"James<PASSWORD>aly")
expect(parse_string("/Ja#6des").parse_token).to eql(:"James")
expect(parse_string("/Ja#6des").parse_token).to eql(:"James")
end
# '/' is a valid PDF name, but :"" is only a valid ruby symbol in 1.9
# On 1.8 VMs the best I can do is a string with a single space. This
# is bound to cause trouble but it's better than treating empty PDF
# Names as a syntax error
if RUBY_VERSION >= "1.9"
it "should parse an empty name correctly" do
expect(parse_string("/").parse_token).to eql("".to_sym)
parser = parse_string("/\n/")
expect(parser.parse_token).to eql("".to_sym)
expect(parser.parse_token).to eql("".to_sym)
end
it "should parse two empty names correctly" do
parser = parse_string("/ /")
expect(parser.parse_token).to eql("".to_sym)
expect(parser.parse_token).to eql("".to_sym)
end
else
it "should parse an empty name correctly" do
expect(parse_string("/").parse_token).to eql(:" ")
parser = parse_string("/\n/")
expect(parser.parse_token).to eql(:" ")
expect(parser.parse_token).to eql(:" ")
end
it "should parse two empty names correctly" do
parser = parse_string("/ /")
expect(parser.parse_token).to eql(:" ")
expect(parser.parse_token).to eql(:" ")
end
end
it "should parse booleans correctly" do
expect(parse_string("true").parse_token).to be_truthy
expect(parse_string("false").parse_token).to be_falsey
end
it "should parse null and nil correctly" do
expect(parse_string("").parse_token).to be_nil
expect(parse_string("null").parse_token).to be_nil
end
it "should parse a string correctly" do
expect(parse_string("()").parse_token).to eql("")
expect(parse_string("(this is a string)").parse_token).to eql("this is a string")
expect(parse_string("(this \\n is a string)").parse_token).to eql("this \n is a string")
expect(parse_string("(x \\t x)").parse_token).to eql("x \t x")
expect(parse_string("(x \\101 x)").parse_token).to eql("x A x")
expect(parse_string("(x \\61 x)").parse_token).to eql("x 1 x")
expect(parse_string("(x \\1 x)").parse_token).to eql("x \x01 x")
expect(parse_string("(x \\( x)").parse_token).to eql("x ( x")
expect(parse_string("((x)))").parse_token).to eql("(x)")
expect(parse_string("(Adobe)").parse_token).to eql("Adobe")
expect(parse_string("(!\"%1)").parse_token).to eql("!\"%1")
expect(parse_string("(James\\ Healy)").parse_token).to eql("James Healy")
expect(parse_string("(x\nx)").parse_token).to eql("x\nx")
expect(parse_string("(x\rx)").parse_token).to eql("x\nx")
expect(parse_string("(x\r\nx)").parse_token).to eql("x\nx")
expect(parse_string("(x\\rx)").parse_token).to eql("x\rx")
expect(parse_string("(\\rx)").parse_token).to eql("\rx")
expect(parse_string("(\\r)").parse_token).to eql("\r")
expect(parse_string("(x\n\rx)").parse_token).to eql("x\nx")
expect(parse_string("(x \\\nx)").parse_token).to eql("x x")
expect(parse_string("(\\\\f)").parse_token).to eql("\\f")
expect(parse_string("([test])").parse_token).to eql("[test]")
end
it "should parse a Unicode string correctly" do
seq = {
# key source expected confusing to
:straddle_seq_5c6e =>["\x4F\x5C\x5C\x6E\x05", "\x4F\x5C\x6E\x05"], # /.\n./
:straddle_seq_5c72 =>["\x4F\x5C\x5C\x72\x06", "\x4F\x5C\x72\x06"], # /.\r./
:straddle_seq_5c74 =>["\x4F\x5C\x5C\x74\x06", "\x4F\x5C\x74\x06"], # /.\t./
:straddle_seq_5c62 =>["\x4F\x5C\x5C\x62\x10", "\x4F\x5C\x62\x10"], # /.\b./
:straddle_seq_5c66 =>["\x4F\x5C\x5C\x66\xFF", "\x4F\x5C\x66\xFF"], # /.\f./
:char_5c08 =>["\x5C\x5C\x08", "\x5C\x08"], # /\\\b/
:char_5c09 =>["\x5C\x5C\x09", "\x5C\x09"], # /\\\t/
:char_5c0a =>["\x5C\x5C\x5C\x6E", "\x5C\x0A"], # /\\\n/
:char_5c0d =>["\x5C\x5C\x5C\x72", "\x5C\x0D"], # /\\\r/
:char_5c28 =>["\x5C\x5C\x5C\x28", "\x5C\x28"], # /\\(/
:char_5c6e =>["\x5C\x5C\x6E", "\x5C\x6E"], # /\\n/
:char_5c02 =>["\x5C\x5C\x02", "\x5C\x02"], # /\\./
:char_5c71 =>["\x5C\x5C\x71", "\x5C\x71"], # /\\./
:char_contain_08 =>["\x4E\x08", "\x4E\x08"], # /.\b/
:char_contain_09 =>["\x4E\x09", "\x4E\x09"], # /.\t/
:char_contain_0a =>["\x4E\x5C\x6E", "\x4E\x0A"], # /.\n/
:char_contain_0c =>["\x54\x0C", "\x54\x0C"], # /.\f/
:char_contain_0d =>["\x69\x5C\x72", "\x69\x0D"], # /.\r/
:char_contain_28 =>["\x75\x5C\x28", "\x75\x28"], # /.(/
:char_contain_29 =>["\x52\x5C\x29", "\x52\x29"], # /.)/
}
bom = "\xFE\xFF"
seq.each_value do |(src, exp)|
src = binary_string("(#{bom}#{src})")
exp = binary_string("#{bom}#{exp}")
expect(parse_string(src).parse_token).to eql(exp)
end
mixed = [ seq[:straddle_seq_5c6e], seq[:char_5c08], seq[:char_5c0a], seq[:char_5c02], seq[:char_contain_0a] ]
mixed_src = binary_string("(" + bom + mixed.map {|x| x[0]}.join + ")")
mixed_exp = binary_string(bom + mixed.map {|x| x[1]}.join)
expect(parse_string(mixed_src).parse_token).to eql(mixed_exp)
end
it "should not leave the closing literal string delimiter in the buffer after parsing a string" do
parser = parse_string("(this is a string) /James")
expect(parser.parse_token).to eql("this is a string")
expect(parser.parse_token).to eql(:James)
end
it "should parse a hex string correctly" do
expect(parse_string("<48656C6C6F>").parse_token).to eql("Hello")
end
it "should ignore whitespace when parsing a hex string" do
expect(parse_string("<48656C6C6F20\n4A616D6573>").parse_token).to eql("Hello James")
end
it "should parse dictionary with embedded hex string correctly" do
dict = parse_string("<< /X <48656C6C6F> >>").parse_token
expect(dict.size).to eql(1)
expect(dict[:X]).to eql("Hello")
end
it "should parse various dictionaries correctly" do
str = "<< /Registry (Adobe) /Ordering (Japan1) /Supplement 5 >>"
dict = parse_string(str).parse_token
expect(dict.size).to eql(3)
expect(dict[:Registry]).to eql("Adobe")
expect(dict[:Ordering]).to eql("Japan1")
expect(dict[:Supplement]).to eql(5)
end
it "should parse dictionary with extra space ok" do
str = "<<\r\n/Type /Pages\r\n/Count 3\r\n/Kids [ 25 0 R 27 0 R]\r\n \r\n>>"
dict = parse_string(str).parse_token
expect(dict.size).to eq(3)
end
it "should parse an array correctly" do
expect(parse_string("[ 10 0 R 12 0 R ]").parse_token.size).to eql(2)
end
it "should parse numbers correctly" do
parser = parse_string("1 2 -3 4.5 -5")
expect(parser.parse_token).to eql( 1)
expect(parser.parse_token).to eql( 2)
expect(parser.parse_token).to eql(-3)
expect(parser.parse_token).to eql( 4.5)
expect(parser.parse_token).to eql(-5)
end
end
|
dexcodeinc/pdf-reader
|
lib/pdf/reader/synchronized_cache.rb
|
<filename>lib/pdf/reader/synchronized_cache.rb
# encoding: utf-8
# utilities.rb : General-purpose utility classes which don't fit anywhere else
#
# Copyright August 2012, <NAME>. All Rights Reserved.
#
# This is free software. Please see the LICENSE and COPYING files for details.
#
# This was originally written for the prawn gem.
require 'thread'
class PDF::Reader
# Throughout the pdf-reader codebase, repeated calculations which can benefit
# from caching are made In some cases, caching and reusing results can not
# only save CPU cycles but also greatly reduce memory requirements But at the
# same time, we don't want to throw away thread safety We have two
# interchangeable thread-safe cache implementations:
class SynchronizedCache
def initialize
@cache = {}
@mutex = Mutex.new
end
def [](key)
@mutex.synchronize { @cache[key] }
end
def []=(key,value)
@mutex.synchronize { @cache[key] = value }
end
end
end
|
dexcodeinc/pdf-reader
|
spec/font_descriptor_spec.rb
|
<gh_stars>0
# coding: utf-8
require "spec_helper"
describe PDF::Reader::FontDescriptor, "initialisation" do
let!(:dict) do
{
:Ascent => 10,
:Descent => 10,
:MissingWidth => 500,
:FontBBox => [0, 0, 10, 10],
:AvgWidth => 40,
:CapHeight => 30,
:Flags => 1,
:ItalicAngle => 0,
:FontName => :Helvetica,
:Leading => 0,
:MaxWidth => 500,
:StemV => 0,
:XHeight => 0,
:FontStretch => :Condensed,
:FontWeight => 500,
:FontFamily => :BoldItalic
}
end
let!(:objects) { PDF::Reader::ObjectHash.allocate }
subject { PDF::Reader::FontDescriptor.new(objects, dict)}
it "should set the correct instance vars" do
expect(subject.ascent).to eq(10)
expect(subject.descent).to eq(10)
expect(subject.missing_width).to eq(500)
expect(subject.font_bounding_box).to eq([0,0, 10, 10])
expect(subject.avg_width).to eq(40)
expect(subject.cap_height).to eq(30)
expect(subject.font_flags).to eq(1)
expect(subject.italic_angle).to eq(0)
expect(subject.font_name).to eq("Helvetica")
expect(subject.leading).to eq(0)
expect(subject.max_width).to eq(500)
expect(subject.stem_v).to eq(0)
expect(subject.x_height).to eq(0)
expect(subject.font_stretch).to eq(:Condensed)
expect(subject.font_weight).to eq(500)
expect(subject.font_family).to eq(:BoldItalic)
end
end
describe PDF::Reader::FontDescriptor, "#glyph_width" do
skip
end
describe PDF::Reader::FontDescriptor, "#glyph_to_pdf_scale_factor" do
skip
end
|
leahjs/my-reminder-app
|
app/models/appointmentreminder.rb
|
<filename>app/models/appointmentreminder.rb<gh_stars>0
class Appointmentreminder < ActiveRecord::Base
end
|
leahjs/my-reminder-app
|
app/views/appointmentreminders/index.json.jbuilder
|
json.array!(@appointmentreminders) do |appointmentreminder|
json.extract! appointmentreminder, :id
json.url appointmentreminder_url(appointmentreminder, format: :json)
end
|
dylanahsmith/resque
|
lib/resque/coder.rb
|
module Resque
class EncodeException < StandardError; end
class DecodeException < StandardError; end
class Coder
# Given a Ruby object, returns a string suitable for storage in a
# queue.
def encode(object)
raise EncodeException
end
# alias for encode
def dump(object)
encode(object)
end
# Given a string, returns a Ruby object.
def decode(object)
raise DecodeException
end
# alias for decode
def load(object)
decode(object)
end
end
end
|
dylanahsmith/resque
|
test/resque_test.rb
|
require 'test_helper'
describe "Resque" do
include Test::Unit::Assertions
before do
Resque.redis.flushall
Resque.push(:people, { 'name' => 'chris' })
Resque.push(:people, { 'name' => 'bob' })
Resque.push(:people, { 'name' => 'mark' })
@original_redis = Resque.redis
end
after do
Resque.redis = @original_redis
end
it "can set a namespace through a url-like string" do
assert Resque.redis
assert_equal :resque, Resque.redis.namespace
Resque.redis = 'localhost:9736/namespace'
assert_equal 'namespace', Resque.redis.namespace
end
it "redis= works correctly with a Redis::Namespace param" do
new_redis = Redis.new(:host => "localhost", :port => 9736)
new_namespace = Redis::Namespace.new("namespace", :redis => new_redis)
Resque.redis = new_namespace
assert_equal new_namespace, Resque.redis
Resque.redis = 'localhost:9736/namespace'
end
it "can put jobs on a queue" do
assert Resque::Job.create(:jobs, 'SomeJob', 20, '/tmp')
assert Resque::Job.create(:jobs, 'SomeJob', 20, '/tmp')
end
it "can grab jobs off a queue" do
Resque::Job.create(:jobs, 'some-job', 20, '/tmp')
job = Resque.reserve(:jobs)
assert_kind_of Resque::Job, job
assert_equal SomeJob, job.payload_class
assert_equal 20, job.args[0]
assert_equal '/tmp', job.args[1]
end
it "can re-queue jobs" do
Resque::Job.create(:jobs, 'some-job', 20, '/tmp')
job = Resque.reserve(:jobs)
job.recreate
assert_equal job, Resque.reserve(:jobs)
end
it "can put jobs on a queue by way of an ivar" do
assert_equal 0, Resque.size(:ivar)
assert Resque.enqueue(SomeIvarJob, 20, '/tmp')
assert Resque.enqueue(SomeIvarJob, 20, '/tmp')
job = Resque.reserve(:ivar)
assert_kind_of Resque::Job, job
assert_equal SomeIvarJob, job.payload_class
assert_equal 20, job.args[0]
assert_equal '/tmp', job.args[1]
assert Resque.reserve(:ivar)
assert_equal nil, Resque.reserve(:ivar)
end
it "can remove jobs from a queue by way of an ivar" do
assert_equal 0, Resque.size(:ivar)
assert Resque.enqueue(SomeIvarJob, 20, '/tmp')
assert Resque.enqueue(SomeIvarJob, 30, '/tmp')
assert Resque.enqueue(SomeIvarJob, 20, '/tmp')
assert Resque::Job.create(:ivar, 'blah-job', 20, '/tmp')
assert Resque.enqueue(SomeIvarJob, 20, '/tmp')
assert_equal 5, Resque.size(:ivar)
assert Resque.dequeue(SomeIvarJob, 30, '/tmp')
assert_equal 4, Resque.size(:ivar)
assert Resque.dequeue(SomeIvarJob)
assert_equal 1, Resque.size(:ivar)
end
it "jobs have a nice #inspect" do
assert Resque::Job.create(:jobs, 'SomeJob', 20, '/tmp')
job = Resque.reserve(:jobs)
assert_equal '(Job{jobs} | SomeJob | [20, "/tmp"])', job.inspect
end
it "jobs can be destroyed" do
assert Resque::Job.create(:jobs, 'SomeJob', 20, '/tmp')
assert Resque::Job.create(:jobs, 'BadJob', 20, '/tmp')
assert Resque::Job.create(:jobs, 'SomeJob', 20, '/tmp')
assert Resque::Job.create(:jobs, 'BadJob', 30, '/tmp')
assert Resque::Job.create(:jobs, 'BadJob', 20, '/tmp')
assert_equal 5, Resque.size(:jobs)
assert_equal 2, Resque::Job.destroy(:jobs, 'SomeJob')
assert_equal 3, Resque.size(:jobs)
assert_equal 1, Resque::Job.destroy(:jobs, 'BadJob', 30, '/tmp')
assert_equal 2, Resque.size(:jobs)
end
it "jobs can it for equality" do
assert Resque::Job.create(:jobs, 'SomeJob', 20, '/tmp')
assert Resque::Job.create(:jobs, 'some-job', 20, '/tmp')
assert_equal Resque.reserve(:jobs), Resque.reserve(:jobs)
assert Resque::Job.create(:jobs, 'SomeMethodJob', 20, '/tmp')
assert Resque::Job.create(:jobs, 'SomeJob', 20, '/tmp')
assert_not_equal Resque.reserve(:jobs), Resque.reserve(:jobs)
assert Resque::Job.create(:jobs, 'SomeJob', 20, '/tmp')
assert Resque::Job.create(:jobs, 'SomeJob', 30, '/tmp')
assert_not_equal Resque.reserve(:jobs), Resque.reserve(:jobs)
end
it "can put jobs on a queue by way of a method" do
assert_equal 0, Resque.size(:method)
assert Resque.enqueue(SomeMethodJob, 20, '/tmp')
assert Resque.enqueue(SomeMethodJob, 20, '/tmp')
job = Resque.reserve(:method)
assert_kind_of Resque::Job, job
assert_equal SomeMethodJob, job.payload_class
assert_equal 20, job.args[0]
assert_equal '/tmp', job.args[1]
assert Resque.reserve(:method)
assert_equal nil, Resque.reserve(:method)
end
it "can define a queue for jobs by way of a method" do
assert_equal 0, Resque.size(:method)
assert Resque.enqueue_to(:new_queue, SomeMethodJob, 20, '/tmp')
job = Resque.reserve(:new_queue)
assert_equal SomeMethodJob, job.payload_class
assert_equal 20, job.args[0]
assert_equal '/tmp', job.args[1]
end
it "needs to infer a queue with enqueue" do
assert_raises Resque::NoQueueError do
Resque.enqueue(SomeJob, 20, '/tmp')
end
end
it "validates job for queue presence" do
assert_raises Resque::NoQueueError do
Resque.validate(SomeJob)
end
end
it "can put items on a queue" do
assert Resque.push(:people, { 'name' => 'jon' })
end
it "can pull items off a queue" do
assert_equal({ 'name' => 'chris' }, Resque.pop(:people))
assert_equal({ 'name' => 'bob' }, Resque.pop(:people))
assert_equal({ 'name' => 'mark' }, Resque.pop(:people))
assert_equal nil, Resque.pop(:people)
end
it "knows how big a queue is" do
assert_equal 3, Resque.size(:people)
assert_equal({ 'name' => 'chris' }, Resque.pop(:people))
assert_equal 2, Resque.size(:people)
assert_equal({ 'name' => 'bob' }, Resque.pop(:people))
assert_equal({ 'name' => 'mark' }, Resque.pop(:people))
assert_equal 0, Resque.size(:people)
end
it "can peek at a queue" do
assert_equal({ 'name' => 'chris' }, Resque.peek(:people))
assert_equal 3, Resque.size(:people)
end
it "can peek multiple items on a queue" do
assert_equal({ 'name' => 'bob' }, Resque.peek(:people, 1, 1))
assert_equal([{ 'name' => 'bob' }, { 'name' => 'mark' }], Resque.peek(:people, 1, 2))
assert_equal([{ 'name' => 'chris' }, { 'name' => 'bob' }], Resque.peek(:people, 0, 2))
assert_equal([{ 'name' => 'chris' }, { 'name' => 'bob' }, { 'name' => 'mark' }], Resque.peek(:people, 0, 3))
assert_equal({ 'name' => 'mark' }, Resque.peek(:people, 2, 1))
assert_equal nil, Resque.peek(:people, 3)
assert_equal [], Resque.peek(:people, 3, 2)
end
it "knows what queues it is managing" do
assert_equal %w( people ), Resque.queues
Resque.push(:cars, { 'make' => 'bmw' })
assert_equal %w( cars people ), Resque.queues
end
it "queues are always a list" do
Resque.redis.flushall
assert_equal [], Resque.queues
end
it "can delete a queue" do
Resque.push(:cars, { 'make' => 'bmw' })
assert_equal %w( cars people ), Resque.queues
Resque.remove_queue(:people)
assert_equal %w( cars ), Resque.queues
assert_equal nil, Resque.pop(:people)
end
it "keeps track of resque keys" do
assert_equal ["queue:people", "queues"].sort, Resque.keys.sort
end
it "badly wants a class name, too" do
assert_raises Resque::NoClassError do
Resque::Job.create(:jobs, nil)
end
end
it "keeps stats" do
Resque::Job.create(:jobs, SomeJob, 20, '/tmp')
Resque::Job.create(:jobs, BadJob)
Resque::Job.create(:jobs, GoodJob)
Resque::Job.create(:others, GoodJob)
Resque::Job.create(:others, GoodJob)
stats = Resque.info
assert_equal 8, stats[:pending]
@worker = Resque::Worker.new(:jobs)
@worker.register_worker
2.times { @worker.process }
job = @worker.reserve
@worker.working_on job
stats = Resque.info
assert_equal 1, stats[:working]
assert_equal 1, stats[:workers]
@worker.done_working
stats = Resque.info
assert_equal 3, stats[:queues]
assert_equal 3, stats[:processed]
assert_equal 1, stats[:failed]
if ENV.key? 'RESQUE_DISTRIBUTED'
assert_equal [Resque.redis.respond_to?(:server) ? 'localhost:9736, localhost:9737' : 'redis://localhost:9736/0, redis://localhost:9737/0'], stats[:servers]
else
assert_equal [Resque.redis.respond_to?(:server) ? 'localhost:9736' : 'redis://localhost:9736/0'], stats[:servers]
end
end
it "decode bad json" do
assert_raises Resque::DecodeException do
Resque.coder.decode("{\"error\":\"Module not found \\u002\"}")
end
end
it "inlining jobs" do
begin
Resque.inline = true
Resque.enqueue(SomeIvarJob, 20, '/tmp')
assert_equal 0, Resque.size(:ivar)
ensure
Resque.inline = false
end
end
it 'treats symbols and strings the same' do
assert_equal Resque.queue(:people), Resque.queue('people')
end
end
|
dylanahsmith/resque
|
lib/resque/multi_json_coder.rb
|
<gh_stars>1-10
require 'multi_json'
require 'resque/coder'
# OkJson won't work because it doesn't serialize symbols
# in the same way yajl and json do.
if MultiJson.respond_to?(:adapter)
raise "Please install the yajl-ruby or json gem" if MultiJson.adapter.to_s == 'MultiJson::Adapters::OkJson'
elsif MultiJson.respond_to?(:engine)
raise "Please install the yajl-ruby or json gem" if MultiJson.engine.to_s == 'MultiJson::Engines::OkJson'
end
module Resque
class MultiJsonCoder < Coder
def encode(object)
if MultiJson.respond_to?(:dump) && MultiJson.respond_to?(:load)
MultiJson.dump object
else
MultiJson.encode object
end
end
def decode(object)
return unless object
begin
if MultiJson.respond_to?(:dump) && MultiJson.respond_to?(:load)
MultiJson.load object
else
MultiJson.decode object
end
rescue ::MultiJson::DecodeError => e
raise DecodeException, e.message, e.backtrace
end
end
end
end
|
dylanahsmith/resque
|
lib/resque/version.rb
|
<gh_stars>100-1000
module Resque
Version = VERSION = '1.20.0'
end
|
dylanahsmith/resque
|
lib/resque/failure/airbrake.rb
|
begin
require 'airbrake'
rescue LoadError
raise "Can't find 'airbrake' gem. Please add it to your Gemfile or install it."
end
require 'resque/failure/thoughtbot'
module Resque
module Failure
class Airbrake < Base
include Resque::Failure::Thoughtbot
@klass = ::Airbrake
end
end
end
|
JMuscutt/cwe-library-notifications
|
app/models/record_mailer.rb
|
<reponame>JMuscutt/cwe-library-notifications<gh_stars>0
# -*- encoding : utf-8 -*-
# Only works for documents with a #to_marc right now.
class RecordMailer < ActionMailer::Base
def email_record(documents, details, url_gen_params)
#raise ArgumentError.new("RecordMailer#email_record only works with documents with a #to_marc") unless document.respond_to?(:to_marc)
subject = I18n.t('blacklight.email.text.subject', :count => documents.length, :title => (documents.first.to_semantic_values[:title] rescue 'N/A') )
@documents = documents
@message = details[:message]
@url_gen_params = url_gen_params
mail(:to => details[:to], :subject => subject, :from => '<EMAIL>')
end
def sms_record(documents, details, url_gen_params)
@documents = documents
@url_gen_params = url_gen_params
mail(:to => details[:to], :subject => "LBCC Library item", :from => '<EMAIL>')
end
end
|
JMuscutt/cwe-library-notifications
|
app/models/article_facet.rb
|
# Represents a facet for article searches
class ArticleFacet
attr_reader :title, :values
# Create a new facet
def initialize title
@title = title
@values = Array.new
end
# Add a new value to an existing facet
def add_value value, action, count
tmp = Hash.new
tmp[:value] = value
tmp[:action] = action
tmp[:count] = count
@values.push(tmp)
end
end
|
JMuscutt/cwe-library-notifications
|
app/controllers/cover_images_controller.rb
|
# A controller that fetches cover images from OpenLibrary and
# caches them using the ActiveRecord model
module CoverImagesController
require 'net/http'
# Returns a URL if it can find a cover image for the document
# Otherwise returns false
def cover_image_url_for document
cover = CoverImage.find_by(solr_id: document.id)
identifiers = find_identifiers_from document
if cover
if recent_enough? cover.updated_at
if cover.thumbnail_url
return cover.thumbnail_url
end
else
updated = update_cache identifiers, cover
return updated if updated
end
else
# If the image has not yet been cached
new_cover = fetch_new_cover identifiers, document.id
return new_cover if new_cover
end
return false
end
private
# Extracts an array of a given type of identifier from the
# solr document
def extract_identifiers document, solr_label
identifiers = []
if document.has? solr_label
case document[solr_label]
when Array then identifiers = document[solr_label]
when String then identifiers.push(document[solr_label])
else
identifiers = document[solr_label].to_a
end
end
return identifiers
end
# Returns a URI for a thumbnail image if it can find one,
# otherwise it returns false
# If it was successful, it also caches the URI
# If it was unsuccessful, it caches the solr_id with a thumbnail_url=NULL
def fetch_new_cover identifiers, id
identifiers[:isbns].each do |isbn|
thumbnail_url = get_image_url(isbn, 'isbn', 'S')
if thumbnail_url
full_url = get_image_url(isbn, 'isbn', 'M')
image = CoverImage.create(isbn: isbn, thumbnail_url: thumbnail_url, full_url: full_url, solr_id: id)
if image.valid?
return thumbnail_url
end
end
end
begin
image = CoverImage.create(solr_id: id)
rescue ActiveRecord::JDBCError
end
return false
end
# Creates a hash containing three arrays of identifiers
# for ISBNs, OCLC numbers, and LCCNs
def find_identifiers_from document
identifiers = { isbns: extract_identifiers(document, 'isbn_t'),
oclcns: extract_identifiers(document, 'oclcn_t'),
lccns: extract_identifiers(document, 'lccn_t') }
return identifiers
end
# Returns a URI object for an image from the Open Library.
# identifier_type can be ISBN, OCLC, or LCCN (case-
# insensitive).
#
# Returns a URL if successful, false if not
def get_image_url identifier, identifier_type, size
begin
return URI.parse('https://covers.openlibrary.org/b/' + identifier_type + '/' + identifier + '-' + size + '.jpg?default=false')
rescue
return false
end
end
# Check to make sure the cache isn't older than 3 weeks
def recent_enough? updated_at
return 3.weeks.ago.to_i < updated_at.to_time.to_i
end
# Search for cover images for an existing solr id
# and update the cache accordingly
#
# Returns a thumbnail URL if an image was found, false if not
def update_cache identifiers, cover
identifiers[:isbns].each do |isbn|
thumbnail_url = get_image_url(isbn, 'isbn', 'S')
if thumbnail_url
full_url = get_image_url(isbn, 'isbn', 'M')
cover.update(isbn: isbn, thumbnail_url: thumbnail_url, full_url: full_url)
return thumbnail_url
end
end
return false
end
end
|
JMuscutt/cwe-library-notifications
|
app/helpers/article_helper.rb
|
# Helper functions for displaying journal/news articles
module ArticleHelper
def display_article_type(original_string)
article_type = original_string.capitalize
unless article_type.include? 'article'
article_type += ' article'
end
return article_type
end
end
|
JMuscutt/cwe-library-notifications
|
app/models/user_fingerprint.rb
|
<gh_stars>0
class UserFingerprint < ActiveRecord::Base
visitable
validates_uniqueness_of :visit_id
end
|
JMuscutt/cwe-library-notifications
|
test/models/user_test.rb
|
require 'test_helper'
class UserTest < ActiveSupport::TestCase
fixtures :user
# test "the truth" do
# assert true
# end
end
|
JMuscutt/cwe-library-notifications
|
app/models/article.rb
|
<filename>app/models/article.rb
# Journal and newspaper articles taken from an external API
class Article < SolrDocument
# attr_reader :abstract, :authors, :db, :id, :journal, :title, :type, :url, :year
PROXY_PREFIX = 'http://ezproxy.libweb.linnbenton.edu:2048/login?url='
def extract_data_from record
if record.record['PLink'] and record.title
#if record['PLink'] and record['RecordInfo']['BibRecord']['BibEntity']['Titles'].first['TitleFull']
@_source[:title] = Nokogiri::HTML.parse(record.title).text
@_source[:url_fulltext_display] = [PROXY_PREFIX + record.record['PLink']]
@_source[:db] = record.dbid
@_source[:id] = record.an
if record.pubtype
@_source[:pubtype] = record.pubtype
end
@_source[:authors] = record.authors_raw
@_source[:year] = record.pubyear
extract_journal_name_from_api_response record
record.record['Items'].each do |item|
if 'Abstract' == item['Name']
@_source[:abstract] = Nokogiri::HTML.parse(item['Data']).text
end
end
end
end
private
def extract_journal_name_from_api_response record
begin
@_source[:journal] = record.record['RecordInfo']['BibRecord']['BibRelationships']['IsPartOfRelationships'].first['BibEntity']['Titles'].first['TitleFull']
rescue NoMethodError
@_source[:journal] = "Unknown journal"
end
end
end
|
JMuscutt/cwe-library-notifications
|
test/models/eds_connection_test.rb
|
<reponame>JMuscutt/cwe-library-notifications
require 'test_helper'
require 'securerandom'
require 'pp'
class TestConnectionHandler < EDSApi::ConnectionHandler
def initialize
@session_token = SecureRandom.hex
@auth_token = SecureRandom.hex
end
end
class TestEdsConnection < EdsConnection
attr_reader :raw_connection
attr_writer :last_authentication
def initialize
super
@raw_connection = TestConnectionHandler.new
end
end
class TestUnauthenticatedConnection < EdsConnection
attr_accessor :raw_connection
def initialize
@raw_connection = TestConnectionHandler.new
@raw_connection.auth_token = nil
end
end
class EdsConnectionTest < ActiveSupport::TestCase
setup :initialize_vars
test "When EDS Username is nil, the app will attempt IP authentication" do
Rails.configuration.articles['username'] = nil
@ip_conn = EdsConnection.new
assert_not @ip_conn.using_uid_auth?
end
test "When EDS Username and password are both available in Rails.configuration, the app will attempt UID authentication" do
Rails.configuration.articles['username'] = 'username'
Rails.configuration.articles['password'] = 'password'
conn = EdsConnection.new
assert conn.using_uid_auth?
end
test "When EDS password is unavailable in Rails.configuration, the app will attempt IP authentication" do
Rails.configuration.articles['username'] = 'username'
Rails.configuration.articles.delete('password')
conn = EdsConnection.new
assert_not conn.using_uid_auth?
end
test "When EDS username is unavailable in Rails.configuration, the app will attempt IP authentication" do
Rails.configuration.articles.delete('username')
Rails.configuration.articles['password'] = 'password'
conn = EdsConnection.new
assert_not conn.using_uid_auth?
end
test "UID-authenticated EDS Connection reports that it is ready when both session token and auth token are available" do
Rails.configuration.articles['username'] = 'username'
Rails.configuration.articles['password'] = 'password'
conn = TestEdsConnection.new
assert conn.ready?
end
test "UID-authenticated EDS Connection re-initializes if last_authentication was more than 20 minutes ago" do
Rails.configuration.articles['username'] = 'username'
Rails.configuration.articles['password'] = 'password'
conn = TestEdsConnection.new
first_session_token = conn.raw_connection.show_session_token
conn.last_authentication = 45.minutes.ago
conn.ready?
assert_not_equal first_session_token, conn.raw_connection.show_session_token
end
test "IP-authenticated EDS Connection reports that it is ready when both session token and auth token are available" do
Rails.configuration.articles.delete('username')
Rails.configuration.articles['password'] = 'password'
conn = TestEdsConnection.new
assert conn.ready?
end
test "When no appropriate tokens are available, the EDS Connection object does not report that it is ready" do
conn = TestUnauthenticatedConnection.new
assert_not conn.ready?
end
private
def initialize_vars
Rails.configuration.articles['username'] = nil
@ip_conn = EdsConnection.new
end
end
|
JMuscutt/cwe-library-notifications
|
db/migrate/20151231230715_create_cover_images.rb
|
class CreateCoverImages < ActiveRecord::Migration
def change
create_table :cover_images do |t|
t.string :isbn
t.string :thumbnail_url
t.string :full_url
t.string :solr_id
t.string :oclc_number
t.string :lccn
t.timestamps null: false
end
end
end
|
JMuscutt/cwe-library-notifications
|
test/models/article_search_test.rb
|
<reponame>JMuscutt/cwe-library-notifications
require 'test_helper'
class ArticleSearchTest < ActiveSupport::TestCase
test "Article Search search_opts method returns an array" do
a = ArticleSearch.new 'soap opera', 3, [], nil
assert_instance_of Array, a.search_opts
end
end
|
JMuscutt/cwe-library-notifications
|
app/models/metadata_view_fingerprint.rb
|
<reponame>JMuscutt/cwe-library-notifications
class MetadataViewFingerprint < ActiveRecord::Base
end
|
JMuscutt/cwe-library-notifications
|
app/validators/url_validator.rb
|
<reponame>JMuscutt/cwe-library-notifications
# Checks that URLs stored in the Database actually work
class UrlValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
begin
response = Net::HTTP.get_response(URI.parse(value))
rescue
record.errors[attribute] << 'Could not parse or fetch the URI given'
return false
end
if response.body.include? 'not found'
record.errors[attribute] << 'Image not found'
else
unless ['200', '301', '302'].include? response.code
record.errors[attribute] << 'Server responded not ok'
end
end
end
end
|
JMuscutt/cwe-library-notifications
|
app/controllers/application_controller.rb
|
class ApplicationController < ActionController::Base
require 'ebsco-discovery-service-api'
require 'openssl'
# Adds a few additional behaviors into the application controller
include Blacklight::Controller
layout 'blacklight'
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
before_filter :create_article_api_session
before_filter :create_evergreen_session
before_filter :start_jruby_pg
protected
def create_article_api_session
unless session.key? :article_api_connection
if using_eds?
session[:article_api_connection] = EdsConnection.new
elsif using_worldcat?
session[:article_api_connection] = WorldcatConnection.new
end
end
end
def create_evergreen_session
begin
if session.key? :evergreen_connection
if session[:evergreen_connection] == nil
session[:evergreen_connection] = EvergreenHoldings::Connection.new 'http://libcat.linnbenton.edu'
end
else
session[:evergreen_connection] = EvergreenHoldings::Connection.new 'http://libcat.linnbenton.edu'
end
rescue CouldNotConnectToEvergreenError
session[:evergreen_connection] = nil
end
end
def start_jruby_pg
if Rails.env.production? and ( RUBY_PLATFORM =~ /jruby/ or RUBY_PLATFORM =~ /java/ )
require 'jdbc/postgres'
Jdbc::Postgres.load_driver
end
end
private
def using_eds?
return 'eds' == Rails.configuration.articles['api']
end
def using_worldcat?
return 'worldcat' == Rails.configuration.articles['api']
end
end
|
JMuscutt/cwe-library-notifications
|
app/helpers/format_helper.rb
|
# Methods that help figure out what formats the user is interested in
#
# Doesn't really help with views at all, so this should move
module FormatHelper
include BlacklightHelper
def show_all_formats?
return request.parameters[:show_articles] == 'true' ? true : false
end
def show_only_articles?
return request.parameters[:show_articles] == 'only' ? true : false
end
def show_articles?
if (request.parameters.has_key?(:show_articles))
return request.parameters[:show_articles] == 'false' ? false : true
else
return false
end
end
end
|
JMuscutt/cwe-library-notifications
|
db/migrate/20170406175912_add_index_to_cover_images.rb
|
class AddIndexToCoverImages < ActiveRecord::Migration
def change
add_index :cover_images, :solr_id, :unique => true
end
end
|
JMuscutt/cwe-library-notifications
|
app/models/article_search.rb
|
<reponame>JMuscutt/cwe-library-notifications
# Represents a search request in the external articles API and its response
class ArticleSearch < Search
require 'erb'
include ERB::Util
attr_reader :articles, :facets, :search_opts
def enough_data_exists_in(record)
return true
end
# Create a new search object
#
# q: a query string
# page: a page number (can be an int or string)
# requested_facets: an array
# api_connection: and ApiConnection object or one of its descendants
def initialize(q, search_field, page, requested_facets = [], api_connection)
search_fields = {'author' => 'AU', 'title' => 'TI', 'all_fields' => 'TX', 'subject' => 'SU'}
@q = q || 'Linn-Benton Community College'
@search_field_code = search_fields[search_field] || 'TX'
@page = page
@api_connection = api_connection
@articles = Array.new
@requested_facets = requested_facets.to_a
@facets = Array.new
end
# Assemble the requested filters, search options, and defaults for an article search
def search_opts
search_opts = Array.new
search_opts << ['query-1', @search_field_code + ':' + @q.gsub(/[[:punct:]]/, '')] # remove punctuation, because EDS responds poorly to it (particularly : and ,)
search_opts << ['limiter', 'FT:y']
search_opts << ['resultsperpage', '10']
search_opts << ['view', 'detailed']
i = 1
@requested_facets.each do |facet|
search_opts << ['facetfilter', (i.to_s + ', ' + facet)]
i = i + 1
end
search_opts << ['pagenumber', @page.to_s]
search_opts << ['highlight', 'n']
return search_opts
end
def send_search
records = Array.new
if @api_connection.ready?
results = @api_connection.send_search search_opts
if results.records
results.records.each do |record|
if enough_data_exists_in record
current_article = Article.new
current_article.extract_data_from record
records.push current_article
end
end
end
@articles = Kaminari.paginate_array(records, total_count: results.hitcount).page(@page).per(10)
if results.facets.respond_to? :each
results.facets.each do |facet|
tmp = ArticleFacet.new facet['Label']
facet[:values].take(10).each do |value|
tmp.add_value value[:value], value[:action].sub('addfacetfilter(', '').chop, value[:hitcount]
end
@facets.push(tmp)
end
end
end
end
end
|
JMuscutt/cwe-library-notifications
|
app/models/search_fingerprint.rb
|
class SearchFingerprint < ActiveRecord::Base
visitable
after_create :create_user_fingerprint
private
def create_user_fingerprint
unless self.visit.nil?
if self.visit.has_attribute? 'id'
fingerprint_already_exists = UserFingerprint.find_by_visit_id(self.visit.id)
unless fingerprint_already_exists
UserFingerprint.create do |uf|
unless self.visit.ip.empty?
if ['127.0.0.1', '0:0:0:0:0:0:0:1'].include? self.visit.ip
uf.bot_visitor = false
uf.in_district = true
uf.localhost = true
uf.on_campus = true
elsif (/^(192\.168|140.211.14|192.168.127.12|172.16.17.32)[.0-9]*/ =~ self.visit.ip)
uf.bot_visitor = false
uf.in_district = true
uf.localhost = false
uf.on_campus = true
else
uf.localhost = false
uf.on_campus = false
end
end
if self.visit.postal_code
uf.postal_code = self.visit.postal_code
if ['97321', '97322', '97324', '97326', '97327', '97329', '97330', '97331', '97333', '97335', '97336', '97339', '97345', '97346', '97348', '97350', '97355', '97358', '97360', '97361', '97370', '97374', '97377', '97383', '97386', '97389', '97446', '97456'].include? self.visit.postal_code
uf.in_district = true
else
uf.in_district = false
end
end
end
end
end
end
end
end
|
JMuscutt/cwe-library-notifications
|
db/migrate/20170310223711_create_metadata_view_fingerprints.rb
|
<filename>db/migrate/20170310223711_create_metadata_view_fingerprints.rb<gh_stars>0
class CreateMetadataViewFingerprints < ActiveRecord::Migration
def change
create_table :metadata_view_fingerprints do |t|
t.text :document_id
t.text :database_code
t.timestamps null: false
end
end
end
|
JMuscutt/cwe-library-notifications
|
app/models/eds_connection.rb
|
<reponame>JMuscutt/cwe-library-notifications
require 'openssl'
# Connect to an external API to get some articles
class EdsConnection < ArticleConnection
# Create an initial connection to the API
def initialize
@auth_method = :ip
@raw_connection = EDSApi::ConnectionHandler.new(2)
if using_uid_auth?
@auth_method = :uid
@raw_connection.uid_init(
Rails.configuration.articles['username'],
Rails.configuration.articles['password'],
'edsapi')
@raw_connection.uid_authenticate
@last_authentication = Time.current
else
begin
@raw_connection.ip_init 'edsapi'
@raw_connection.ip_authenticate
rescue NoMethodError
end
end
@raw_connection.create_session
end
def ready?
if @raw_connection.show_session_token and @raw_connection.show_auth_token
if @auth_method == :uid
if @last_authentication < 20.minutes.ago
initialize
end
end
return true
end
return false
end
# Fetch a single article from the external API
def retrieve_single_article db, id
article_identifiers = {'dbid' => db, 'an' => id}
return @raw_connection.retrieve article_identifiers
end
# Send an entire search, and return the JSON data produced by
# the EDS API
def send_search search_opts
begin
return @raw_connection.search search_opts
rescue ActionView::Template::Error, Net::ReadTimeout
return handle_timeout
end
end
# Return true if the configuration of the rails app is suitable
# for username/password authentication for the API
def using_uid_auth?
if Rails.configuration.articles['username'].nil? or Rails.configuration.articles['password'].nil?
return false
else
return true
end
end
private
def handle_timeout
logger.debug "EDS timed out"
return false
end
end
|
JMuscutt/cwe-library-notifications
|
db/migrate/20170310223240_create_user_fingerprints.rb
|
class CreateUserFingerprints < ActiveRecord::Migration
def change
create_table :user_fingerprints do |t|
t.boolean :on_campus
t.boolean :in_district
t.boolean :localhost
t.boolean :bot_visitor
t.text :postal_code
t.references :visit, type: :uuid, index: { unique: true }
t.timestamps null: false
end
end
end
|
JMuscutt/cwe-library-notifications
|
app/models/cover_image.rb
|
<filename>app/models/cover_image.rb
# A model to store cover images
class CoverImage < ActiveRecord::Base
extend ActiveModel::Callbacks
include ActiveModel::Validations
include ActiveModel::Validations::Callbacks
before_validation :check_for_redirection
validates :solr_id, presence: true
validates :thumbnail_url, allow_blank: true, url: true
private
# Make sure that the image is not a 302
def check_for_redirection
begin
response = Net::HTTP.get_response(self.thumbnail_url)
rescue
return :abort
end
if '302' == response.code
self.thumbnail_url = response['location']
end
end
end
|
JMuscutt/cwe-library-notifications
|
test/helpers/article_helper_test.rb
|
require 'test_helper'
require Rails.root.join('app', 'helpers', 'data_field_helper').to_s
include DataFieldHelper
class ArticleHelperTest < ActionView::TestCase
test "Article type is a string" do
assert_kind_of String, display_article_type('Journal')
end
end
|
JMuscutt/cwe-library-notifications
|
test/helpers/representative_image_helper_test.rb
|
require 'test_helper'
class RepresentativeImageHelperTest < ActionView::TestCase
test "Article icon is a file and exists" do
assert Rails.root.join('app', 'assets', 'images', format_icon_path('Article')).exist?
end
test "Representative Image Helper provides a link to the article icon" do
article_doc = TestArticleDocument.new
article_doc._source[:db] = 'test'
article_doc._source[:id] = '123'
assert is_valid_link (display_representative_image article_doc)
end
end
|
JMuscutt/cwe-library-notifications
|
app/helpers/data_field_helper.rb
|
<reponame>JMuscutt/cwe-library-notifications
# These helpers help with extracting and formatting
# data about Solr documents and Article API data
module DataFieldHelper
include ActionView::Helpers::TextHelper
require 'uri'
# Make sure that this is an array
def field_to_array(value)
value_arr = []
if value.is_a?(Array)
value_arr = value
elsif value.is_a?(String)
if value.length>0
value_arr.push(value)
end
else
value_arr.push value.to_s
end
return value_arr
end
# Create the HTML to display a field
# from a solr document
def display_field(document, field_name, label, opts = {})
# Make sure that the document actually has the
# desired field
if document.respond_to? field_name
if document.send field_name
values = field_to_array(document.send field_name)
else
return nil
end
elsif document.has? field_name
values = field_to_array(document[field_name])
else
return nil
end
if opts[:dedupe]
if :personal_names == opts[:dedupe]
values.uniq! { |s| s.gsub(/\s?--\s*$/, '').gsub(/^(.*),\s([A-Z]).*\z/, '\2 \1').gsub(/^([a-zA-Z]).*\s([a-zA-z]*)[,\(-\z]/, '\1 \2') }
end
end
values_html = Array.new
values.each do |value|
# Display this field as a link to a search
if opts[:search_link]
# If no search field is specified, default to
# searching all fields
search_field = opts.key?(:search_fields) ? opts[:search_fields] : 'all_fields'
if opts.key?(:exact_match)
value_string = exact_search_catalog_link(strip(value), search_field)
else
value_string = search_catalog_link(strip(value), search_field)
end
elsif opts[:contains_url]
value_string = external_link(value)
else
value_string = value
end
if opts[:snippet]
value_string = snippet :value => value_string
end
# Add a DC RDFa attribute
if opts.key?(:dc_element)
entry = opts[:dc_element].length > 0 ? '<span property="http://purl.org/dc/terms/' + opts[:dc_element] + '">' + value_string + '</span>' : value_string
else
entry = value_string
end
values_html.push(entry)
end
if values_html.any?
display_string = '<dt>' + label + '</dt><dd>' + values_html.join('; ')
return display_string.html_safe
end
end
# Returns an HTML link to a search for the query "text" in quotes
def exact_search_catalog_link text, search_field
return link_to text, url_for(:q => "\"#{text}\"", :search_field => search_field )
end
# Returns an HTML link to a search for the "text" query
def search_catalog_link text, search_field
return link_to text, url_for(:q => text, :search_field => search_field )
end
# Return an HTML <a> tag containing a URL both as its content and its href attribute
def external_link(url)
if url =~ URI::regexp
return link_to url, url
else
return url
end
end
# Provides a shortened version of strings. This is used to cut down particularly
# wordy abstracts to display on search results pages.
# Defaults to producing snippets that are 200 characters or less, but supports an
# option called +:length+ which provides a different number of characters.
#
# snippet :value => "My very short string" # => "My very short string"
# snippet :value => "My very short string", :length => 8 # => "My very"
def snippet opts={}
desired_length = opts[:length] || 200
if opts[:value].is_a? Array
value = opts[:value][0]
else
value = opts[:value]
end
return truncate strip(sanitize value), length: desired_length, separator: ' '
end
# Remove whitespace and punctuation marks from the beginning and end
# of a string
def strip(string)
# Also strip preceeding [ or whitespace
if !string.is_a? String
string = string.to_s
end
string.gsub!(/^[\*\s]*/, '')
string.gsub!(/[,\:;\s]*$/, '')
return string
end
end
|
JMuscutt/cwe-library-notifications
|
lib/tasks/findit.rake
|
namespace :findit do
desc "Install Find It"
task :install do
Bundler.with_clean_env do
sh "bundle install"
end
sh 'rails generate blacklight:assets -s'
sh 'rails generate blacklight:user -s'
sh 'rails generate devise:install -s'
sh 'rake db:migrate RAILS_ENV=development'
sh 'rake db:migrate RAILS_ENV=test'
=begin
ActiveRecord::Base.establish_connection('test')
Rake::Task['db:drop'].invoke
Rake::Task['db:create'].invoke
Rake::Task['db:migrate'].invoke
ActiveRecord::Base.establish_connection('development')
Rake::Task['db:drop'].invoke
Rake::Task['db:create'].invoke
Rake::Task['db:migrate'].invoke
ActiveRecord::Base.establish_connection(ENV['RAILS_ENV'])
=end
end
end
|
JMuscutt/cwe-library-notifications
|
app/models/worldcat_connection.rb
|
<gh_stars>0
# Connect to an external API to get some articles
class WorldcatConnection < ArticleConnection
# Create an initial connection to the API
def initialize
end
def ready?
end
# Fetch a single article from the external API
def retrieve_single_article db, id
end
def send_search search_opts
end
end
|
JMuscutt/cwe-library-notifications
|
db/migrate/20170310211333_create_search_fingerprints.rb
|
<reponame>JMuscutt/cwe-library-notifications
class CreateSearchFingerprints < ActiveRecord::Migration
def change
create_table :search_fingerprints do |t|
t.text :query_string
t.text :facets_used
t.boolean :known_item
t.integer :page
t.references :visit, type: :uuid
t.timestamps null: false
end
end
end
|
JMuscutt/cwe-library-notifications
|
test/helpers/data_field_helper_test.rb
|
<filename>test/helpers/data_field_helper_test.rb
require 'test_helper'
class DataFieldHelperTest < ActionView::TestCase
data_strings = YAML::load_file Rails.root.join('test', 'fixtures', 'data_strings.yml')
test "Convert a string into an array" do
assert_kind_of Array, field_to_array("A Magical String")
end
test "Convert an int into an array" do
assert_kind_of Array, field_to_array(283)
end
test "Convert a Boolean into an array" do
assert_kind_of Array, field_to_array(true)
end
test "field_to_array keeps arrays as they are" do
assert_kind_of Array, field_to_array(["cats", "dogs", "goats", "iguanas"])
end
test "Snippet produces text that is no longer than 200 characters using less than 200 characters" do
assert snippet({Value: data_strings[:short_string]}).length <200
end
test "Snippet produces text that is no longer than 200 characters using exactly 200 characters" do
assert snippet({Value: data_strings[:string_with_200_chars]}).length <200
end
test "Snippet produces text that is no longer than 200 characters using more than 200 characters" do
assert snippet({Value: data_strings[:very_long_string]}).length <200
end
test "external link produces valid HTML link when given a well-formatted URL" do
link = external_link 'http://library.linnbenton.edu/c.php?g=13287&p=2901925'
assert is_valid_link link
end
test "external_link does not produce a link to any poorly-formatted URLs" do
assert external_link 'http://library.linnbenton.edu/c.php?g=13287&p=2901925' !~ /<a\b[^>]*>(.*?)<\/a>/i
end
end
|
JMuscutt/cwe-library-notifications
|
test/helpers/access_options_helper_test.rb
|
<filename>test/helpers/access_options_helper_test.rb
require 'test_helper'
class AccessOptionsHelperTest < ActionView::TestCase
setup :initialize_vars
test "full text access link is a link" do
assert is_valid_link display_fulltext_access_link('http://linnbenton.edu')
end
test "access options for documents with url_fulltext_display is a link" do
assert is_valid_link display_access_options(@short_document)
end
test "concise access options for documents with url_fulltext_display is a link" do
assert is_valid_link display_concise_access_options(@short_document)
end
test "mode_of_access is correct for eg documents" do
assert_equal 'library_holdings', mode_of_access(@long_document)
end
test "mode_of_access is correct for e-resource documents" do
assert_equal 'url', mode_of_access(@short_document)
end
private
def initialize_vars
create_solr_documents
end
end
|
JMuscutt/cwe-library-notifications
|
test/helpers/citation_helper_test.rb
|
require 'test_helper'
class CitationHelperTest < ActionView::TestCase
setup :initialize_vars
test "Test that citations are being returned with 1 element in parseable HTML" do
citations_generated = generate_citations(@short_document)
citations_generated.each do |val|
assert Nokogiri::HTML.parse(val[1])
end
end
test "Test that citations are being returned with 4 elements in parseable HTML" do
citations_generated = generate_citations(@long_document)
citations_generated.each do |val|
assert Nokogiri::HTML.parse(val[1])
end
end
test "Test that citations are generated for the correct documents" do
words_in_citations = []
citations_generated = generate_citations(@long_document)
citations_generated.each do |val|
words = val[1].split
words.each do |word|
if word.length > 3
words_in_citations.push strip_tags(word).downcase.gsub /[[:punct:]]/, ''
end
end
end
words_in_document = ['print', 'online', 'pages', 'page', 'pag']
@words_in_long_document.each do |words|
words.split.each do |word|
words_in_document.push word.downcase.gsub /[[:punct:]]/, ''
end
end
words_in_citations.each do |word|
assert words_in_document.include? word
end
end
protected
def initialize_vars
create_solr_documents
@words_in_long_document = [@book_title, @publisher, @author, @pub_date]
end
end
|
JMuscutt/cwe-library-notifications
|
test/models/cover_image_test.rb
|
<gh_stars>0
require 'test_helper'
class CoverImageTest < ActiveSupport::TestCase
test "Can't cache a cover image without a solr id" do
cover = CoverImage.new thumbnail_url: 'https://covers.openlibrary.org/b/oclc/428817148-M.jpg'
assert_not cover.valid?
end
test "Can't cache a cover image with an invalid URL" do
cover = CoverImage.new solr_id: 12345, thumbnail_url: 'abcdefg'
assert_not cover.valid?
end
test "Can't cache a cover image with a URL that returns a 404" do
cover = CoverImage.new solr_id: 12345, thumbnail_url: 'http://httpstat.us/404'
assert_not cover.valid?
end
test "Can't cache a cover image with a URL that returns a 500" do
cover = CoverImage.new solr_id: 12345, thumbnail_url: 'http://httpstat.us/500'
assert_not cover.valid?
end
test "Can't cache a cover image with a URL that returns a 200 not found message" do
cover = CoverImage.new solr_id: 12345, thumbnail_url: 'https://covers.openlibrary.org/b/isbn/0071381333-S.jpg?default=false'
assert_not cover.valid?
end
test "Can cache a cover image with a proper solr_id and thumbnail_url" do
cover = CoverImage.new solr_id: 12345, thumbnail_url: 'https://ia800808.us.archive.org/zipview.php?zip=/28/items/olcovers68/olcovers68-S.zip&file=686643-S.jpg'
assert cover.valid?
end
end
|
JMuscutt/cwe-library-notifications
|
db/schema.rb
|
<filename>db/schema.rb<gh_stars>0
# encoding: UTF-8
# This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 20170406175912) do
create_table "ahoy_events", force: :cascade do |t|
t.uuid "visit_id", limit: 16
t.integer "user_id"
t.string "name"
t.text "properties"
t.datetime "time"
end
add_index "ahoy_events", ["id"], name: "sqlite_autoindex_ahoy_events_1", unique: true
add_index "ahoy_events", ["time"], name: "index_ahoy_events_on_time"
add_index "ahoy_events", ["user_id"], name: "index_ahoy_events_on_user_id"
add_index "ahoy_events", ["visit_id"], name: "index_ahoy_events_on_visit_id"
create_table "bookmarks", force: :cascade do |t|
t.integer "user_id", null: false
t.string "user_type"
t.string "document_id"
t.string "document_type"
t.binary "title"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "bookmarks", ["document_id"], name: "index_bookmarks_on_document_id"
add_index "bookmarks", ["user_id"], name: "index_bookmarks_on_user_id"
create_table "cover_images", force: :cascade do |t|
t.string "isbn"
t.string "thumbnail_url"
t.string "full_url"
t.string "solr_id"
t.string "oclc_number"
t.string "lccn"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "cover_images", ["solr_id"], name: "index_cover_images_on_solr_id", unique: true
create_table "metadata_view_fingerprints", force: :cascade do |t|
t.text "document_id"
t.text "database_code"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "search_fingerprints", force: :cascade do |t|
t.text "query_string"
t.text "facets_used"
t.boolean "known_item"
t.integer "page"
t.uuid "visit_id", limit: 16
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "searches", force: :cascade do |t|
t.binary "query_params"
t.integer "user_id"
t.string "user_type"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "searches", ["user_id"], name: "index_searches_on_user_id"
create_table "sessions", force: :cascade do |t|
t.string "session_id", null: false
t.text "data"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "sessions", ["session_id"], name: "index_sessions_on_session_id", unique: true
add_index "sessions", ["updated_at"], name: "index_sessions_on_updated_at"
create_table "user_fingerprints", force: :cascade do |t|
t.boolean "on_campus"
t.boolean "in_district"
t.boolean "localhost"
t.boolean "bot_visitor"
t.text "postal_code"
t.uuid "visit_id", limit: 16
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "user_fingerprints", ["visit_id"], name: "index_user_fingerprints_on_visit_id", unique: true
create_table "users", force: :cascade do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0, null: false
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string "current_sign_in_ip"
t.string "last_sign_in_ip"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.boolean "guest", default: false
end
add_index "users", ["email"], name: "index_users_on_email", unique: true
add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
create_table "visits", force: :cascade do |t|
t.uuid "visitor_id", limit: 16
t.string "ip"
t.text "user_agent"
t.text "referrer"
t.text "landing_page"
t.integer "user_id"
t.string "referring_domain"
t.string "search_keyword"
t.string "browser"
t.string "os"
t.string "device_type"
t.integer "screen_height"
t.integer "screen_width"
t.string "country"
t.string "region"
t.string "city"
t.string "postal_code"
t.decimal "latitude"
t.decimal "longitude"
t.string "utm_source"
t.string "utm_medium"
t.string "utm_term"
t.string "utm_content"
t.string "utm_campaign"
t.datetime "started_at"
end
add_index "visits", ["id"], name: "sqlite_autoindex_visits_1", unique: true
add_index "visits", ["user_id"], name: "index_visits_on_user_id"
end
|
JMuscutt/cwe-library-notifications
|
test/helpers/library_holdings_helper_test.rb
|
require 'test_helper'
# A class of tests for displaying availability data from the ILS
#
# Note that many of these rely on very specific titles from LBCC's collection
class LibraryHoldingsHelperTest < ActionView::TestCase
setup :set_session_var
test "simple_library_holdings is parseable HTML" do
assert Nokogiri::HTML.parse(display_simple_library_holdings 346217)
end
test "simple_library_holdings is returning actual results" do
assert_not_equal 'Ask a librarian for information about this item.', display_simple_library_holdings(346217)
end
test "full_library_holdings is parseable HTML" do
assert Nokogiri::HTML.parse(display_full_library_holdings 346217)
end
test "full_library_holdings is returning actual results" do
assert_not_equal 'Ask a librarian for information about this item.', display_full_library_holdings(346217)
end
test "can get status object for a TCN that exists" do
assert_instance_of EvergreenHoldings::Status, get_status(346217)
end
test "get_status returns false if TCN doesn't have attached copies" do
assert_not get_status(1)
end
private
def set_session_var
session[:evergreen_connection] = EvergreenHoldings::Connection.new 'http://libcat.linnbenton.edu'
end
end
|
JMuscutt/cwe-library-notifications
|
test/test_helper.rb
|
require 'coveralls'
Coveralls.wear!
require 'erb'
include ERB::Util
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help'
class ActiveSupport::TestCase
# Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
#fixtures :all
class TestSolrDocument < SolrDocument
attr_writer :_source
end
class TestArticleDocument < Article
attr_writer :_source
end
# Add more helper methods to be used by all tests here...
def create_solr_documents
@book_title = 'The ' + Faker::Pokemon.name + ' from ' + Faker::Pokemon.location
@publisher = 'House ' + Faker::GameOfThrones.house + ' Publishing'
@author = Faker::GameOfThrones.character
@pub_date = Faker::Number.number(4).to_s
@short_document = TestSolrDocument.new
@short_document._source[:title_display] = 'How to eat pudding correctly'
@short_document._source[:url_fulltext_display] = 'http://duckduckgo.com'
@long_document = TestSolrDocument.new
@long_document._source[:eg_tcn_t] = '1234'
@long_document._source[:title_display] = @book_title
@long_document._source[:author_display] = @author
@long_document._source[:pub_date] = Array(@pub_date)
@long_document._source[:publisher_display] = Array(@pub_comp)
end
# Verify that link is parseable, begins with an <a> tag, and ends with a closing </a> tag
def is_valid_link link
unless Nokogiri::HTML.parse link
return false
end
if (link !~ /<a\b[^>]*>(.*?)<\/a>/i)
return false
end
return true
end
end
|
JMuscutt/cwe-library-notifications
|
app/helpers/citation_helper.rb
|
<reponame>JMuscutt/cwe-library-notifications
# Functions related to citations, which might be a bit more sophisticated
# than simple view helpers and should therefore probably be eventually moved
# into model/controller
module CitationHelper
include BlacklightHelper
include ActionView::Helpers::TextHelper
# Creates a one-item BibTeX bibliography in case the app can't find one
# in the data from Solr.
def create_bibtex(document)
biblio = BibTeX::Bibliography.new
biblio << BibTeX::Entry.new( extract_bibliographic_data_from (document))
biblio[0].key = 'resource'
return biblio
end
# Generates a hash containing properly formatted HTML citations
# using CiteProc based on BibTeX data found in a solr index.
def generate_citations(document)
if document.has? 'bibtex_t'
begin
if document['bibtex_t'].is_a?(Array)
b = BibTeX.parse(document['bibtex_t'][0])
elsif document['bibtex_t'].is_a?(String)
b = BibTeX.parse(document['bibtex_t'])
else
b = BibTeX.parse(document['bibtex_t'].to_s)
end
# Creates a minimal BibTeX string from solr data if
# the official BibTeX string can't be parsed.
rescue BibTeX::ParseError
b = create_bibtex document
end
else
# Creates a minimal BibTeX string from solr data if
# there is no BibTeX in the solr document.
b = create_bibtex document
end
styles = Hash.new
citations = Hash.new
# To add a new citation style:
# * the hash key will display in Find It as the label
# for your citation style
# * the style value is the name of the citation style
# as listed at https://github.com/citation-style-language/styles
styles['APA'] = CiteProc::Processor.new format: 'html', style: 'apa'
styles['MLA'] = CiteProc::Processor.new format: 'html', style: 'modern-language-association'
styles['Chicago'] = CiteProc::Processor.new format: 'html', style: 'chicago-fullnote-bibliography'
styles['IEEE'] = CiteProc::Processor.new format: 'html', style: 'ieee'
styles['CSE'] = CiteProc::Processor.new format: 'html', style: 'council-of-science-editors'
# Generates the actual HTML citation using data from the
# variable 'b' (our BibTeX string) and using the styles
# established in the hash 'styles.'
styles.each do |shortname, processor|
processor.import b.to_citeproc
unless processor.empty?
citations[shortname] = processor.render(:bibliography, id: 'resource').first.tr('{}', '')
else
# If CSL mysteriously can't parse the citation,
# just return the metadata from the variable 'b'
# (our BibTeX string.)
citations[shortname] = b
end
end
return citations
end
private
# Returns a hash with the most important information about
# the given solr document
def extract_bibliographic_data_from document
bib_entry = {
bibtex_type: bibtex_type(document['type']),
title: document['title_display'],
}
if document.has? 'author_display'
bib_entry[:author] = document['author_display']
end
if document.has? 'pub_date'
bib_entry[:year] = document['pub_date'][0]
end
if document.has? 'publisher_display'
if document['publisher_display'].is_a?(Array)
bib_entry[:publisher] = document['publisher_display'][0]
else
bib_entry[:publisher] = document['publisher_display'].to_s
end
end
return bib_entry
end
# Returns a symbol representing the BibTeX type that corresponds
# to the string you pass to it
def bibtex_type solr_type
if ['Ebook', 'Book'].include? solr_type
return :book
elsif ['Article'].include? solr_type
return :article
else
return :misc
end
end
end
|
JMuscutt/cwe-library-notifications
|
app/models/article_connection.rb
|
<filename>app/models/article_connection.rb
# Connect to an external API to get some articles
class ArticleConnection
# Create an initial connection to the API
def initialize
end
def ready?
end
# Fetch a single article from the external API
def retrieve_single_article db, id
puts db + id
end
def send_search search_opts
puts search_opts
end
end
|
JMuscutt/cwe-library-notifications
|
app/models/user.rb
|
<filename>app/models/user.rb
class User < ActiveRecord::Base
if Blacklight::Utils.needs_attr_accessible?
attr_accessible :email, :password, :password_confirmation
end
# Connects this user object to Blacklights Bookmarks.
include Blacklight::User
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
# Method added by Blacklight; Blacklight uses #to_s on your
# user class to get a user-displayable login/identifier for
# the account.
def to_s
email
end
end
|
JMuscutt/cwe-library-notifications
|
app/helpers/library_holdings_helper.rb
|
<gh_stars>0
# Displays real-time availability information from the ILS
module LibraryHoldingsHelper
# Returns an HTML representation of the library's holdings attached to a bib record identified by tcn parameter
def display_simple_library_holdings tcn
display_library_holdings = ''
stat = get_status tcn
if stat
if stat.any_copies_available?
display_library_holdings.concat('<a href="http://libcat.linnbenton.edu/eg/opac/record/'+ tcn.to_s + '?locg=8;detail_record_view=1" target="_blank" class="btn btn-success">Available at the library</a>')
display_library_holdings.concat('<table class="table"><thead><tr><th>Status</th><th>Location</th><th>Call number</th></thead>')
stat.copies.first(5).each do |copy|
display_library_holdings.concat copy_information_table_row copy
end
display_library_holdings.concat('</table>')
else
display_library_holdings = '<a href="http://libcat.linnbenton.edu/eg/opac/place_hold?query=locg=8;detail_record_view=1;hold_target=' + tcn.to_s + 'hold_type=T;hold_source_page=/eg/opac/record/'+ tcn.to_s + '?query=locg=8&detail_record_view=1" class="btn btn-warning" target="_blank">Place a hold</a>'
end
else
display_library_holdings.concat 'Ask a librarian for information about this item.'
end
return display_library_holdings.html_safe
end
def display_full_library_holdings tcn
display_library_holdings = ''
stat = get_status tcn
if stat
display_library_holdings = '<h2>Find a copy on the shelf</h2>'
stat.copies.each do |item|
display_library_holdings.concat copy_information_defined_list item
display_library_holdings.concat '<hr />'
end
else
display_library_holdings.concat 'Ask a librarian for information about this item.'
end
return display_library_holdings.html_safe
end
private
def get_status tcn
if session[:evergreen_connection]
stat = session[:evergreen_connection].get_holdings tcn, org_unit: 7
if stat.copies.size > 0
return stat
end
end
return false
end
def copy_information_table_row copy
return content_tag :tr, content_tag(:td, copy.status) + content_tag(:td, copy.location) + content_tag(:td, copy.call_number)
end
def copy_information_defined_list copy
return content_tag :dl,
content_tag(:dt, 'Status') + content_tag(:dd, copy.status) +
content_tag(:dt, 'Location') + content_tag(:dd, copy.location) +
content_tag(:dt, 'Call number') + content_tag(:dd, copy.call_number),
class: 'dl-horizontal dl-invert'
end
end
|
JMuscutt/cwe-library-notifications
|
app/models/search_builder.rb
|
# frozen_string_literal: true
class SearchBuilder < Blacklight::SearchBuilder
include Blacklight::Solr::SearchBuilderBehavior
include BlacklightRangeLimit::RangeLimitBuilder
end
|
JMuscutt/cwe-library-notifications
|
app/helpers/representative_image_helper.rb
|
<reponame>JMuscutt/cwe-library-notifications<filename>app/helpers/representative_image_helper.rb
module RepresentativeImageHelper
# Generates HTML for either a cover image or format
# icon, based on the requested side and identifiers from
# the Solr document
def display_representative_image(document, opts = {})
if document.is_a? Article
return link_to(image_tag(format_icon_path('Article')), controller: 'articles', action: 'show', db: url_encode(document[:db]), id: url_encode(document[:id]))
else
cover_image = cover_image_url_for document
if cover_image
return link_to(image_tag(cover_image, alt:document['title_t'], class: 'thumbnail-cover-image'), :controller => "catalog", :action => "show", :id => document[:id])
elsif document.has? 'format'
return link_to(image_tag(format_icon_path(document['format']), alt:document['title_t'], class: 'thumbnail-cover-image'), :controller => 'catalog', :action => 'show', :id => document.id)
else
return ''
end
end
end
private
# Returns a string with the path of a requested format icon
#
# Note that this method does not actually check if the
# icon exists
def format_icon_path format
return 'icons/'.concat(format).concat('.png')
end
end
|
JMuscutt/cwe-library-notifications
|
test/controllers/cover_images_controller_test.rb
|
<filename>test/controllers/cover_images_controller_test.rb
require 'test_helper'
include CoverImagesController
class CoverImagesControllerTest < ActionController::TestCase
test "Trying to extract identifiers from a non-existant solr field returns a blank array" do
identifiers = extract_identifiers SolrDocument.new, 'dsjfsldjflsdkfjsdlkfjsdlkfjdslkfjsdlfkjsdlkfjsldkfjlskdfs'
assert_instance_of Array, identifiers
end
test "Trying to extract identifiers from a singleton solr field returns an array" do
document = TestSolrDocument.new
document._source[:isbn_t] = '9781595581037'
identifiers = extract_identifiers document, 'isbn_t'
assert_instance_of Array, identifiers
assert_equal 1, identifiers.size
end
test "recent_enough? returns true for recent date" do
assert recent_enough?(1.day.ago.to_s(:db))
end
test "recent_enough? returns false for really old date" do
assert_not recent_enough?(12.years.ago.to_s(:db))
end
test "get_image_url returns a valid HTTPS URI" do
assert_instance_of URI::HTTPS, get_image_url('1234567890', 'ISBN', 'M')
end
end
|
JMuscutt/cwe-library-notifications
|
app/controllers/articles_controller.rb
|
<reponame>JMuscutt/cwe-library-notifications
# This controller coordinates the connection to the external API and handles all the data it returns
class ArticlesController < ApplicationController
after_filter :track_metadata_view, :only => :show
# Create article object named @document and fill it with data from the API so that it's all ready to display
def show
@document = Article.new
if session[:article_api_connection].ready?
results = session[:article_api_connection].retrieve_single_article params[:db], params[:id]
end
if results
@document.extract_data_from results
end
end
protected
def track_metadata_view
MetadataViewFingerprint.create do |mvf|
mvf.document_id = @document.id
mvf.database_code = params[:db]
end
end
end
|
JMuscutt/cwe-library-notifications
|
app/helpers/access_options_helper.rb
|
<reponame>JMuscutt/cwe-library-notifications<gh_stars>0
# Methods that help show users how they can access materials from the Library
module AccessOptionsHelper
include BlacklightHelper
require 'nokogiri'
require 'open-uri'
require 'uri'
# Display how a user can access the resource described in the solr document,
# whether through a physical library copy or a URL
def display_access_options document
mode = mode_of_access document
if mode
if 'library_holdings' == mode
display_full_library_holdings document['eg_tcn_t']
elsif 'url' == mode
return display_fulltext_access_link document['url_fulltext_display'][0]
end
end
end
# Briefly display how a user can access the resource described in the solr document,
# whether through a physical library copy or a URL
#
# This is well suited for the search results display page
def display_concise_access_options document
mode = mode_of_access document
if mode
if 'library_holdings' == mode
display_simple_library_holdings document['eg_tcn_t']
elsif 'url' == mode
return display_fulltext_access_link document['url_fulltext_display'][0]
end
end
end
private
# Return a bootstrap button that links to the given value
def display_fulltext_access_link url
return link_to('Access this resource', URI.encode(url), class: 'btn btn-success', role: 'button', target: '_blank')
end
def mode_of_access document
if document.has? 'eg_tcn_t'
return 'library_holdings'
elsif document.has? 'url_fulltext_display'
return 'url'
else
return false
end
end
end
|
georgemillo/rocketbar_core
|
app/controllers/rocketbar/core/application_controller.rb
|
module Rocketbar
module Core
class ApplicationController < ActionController::Base
end
end
end
|
georgemillo/rocketbar_core
|
lib/rocketbar/core/core.rb
|
<reponame>georgemillo/rocketbar_core<gh_stars>0
require "rocketbar/core/engine"
module Rocketbar
module Core
end
end
|
diegocharles/acts_as_commentable
|
test/models.rb
|
<reponame>diegocharles/acts_as_commentable<filename>test/models.rb
class Post < ApplicationRecord
acts_as_commentable
end
class User < ApplicationRecord
end
class Wall < ApplicationRecord
acts_as_commentable :public, :private
end
|
diegocharles/acts_as_commentable
|
test/schema.rb
|
ActiveRecord::Schema.define(:version => 0) do
create_table :posts do |t|
t.text :text
t.datetime :created_at
t.datetime :updated_at
end
create_table :users do |u|
u.string :name
end
create_table :walls do |w|
w.string :name
end
create_table :comments do |t|
t.string :title, :limit => 50, :default => ""
t.text :comment
t.references :commentable, :polymorphic => true
t.references :user
t.string :role, :default => "comments"
t.timestamps
end
end
|
logicminds/puppet-debugger-graph
|
lib/debugger/graph/version.rb
|
module Debugger
module Graph
VERSION = "0.1.0"
end
end
|
logicminds/puppet-debugger-graph
|
spec/input_responders/graph_spec.rb
|
require 'spec_helper'
require 'puppet-debugger'
require 'puppet-debugger/plugin_test_helper'
describe :graph do
include_examples "plugin_tests"
let(:args) { [] }
it 'works' do
plugin.create_graph_content
# plugin.handle_input("file{'/tmp/test': }")
# expect(output.string).to eq('sdafsda')
end
end
|
logicminds/puppet-debugger-graph
|
lib/plugins/puppet-debugger/input_responders/graph.rb
|
require 'puppet-debugger/input_responder_plugin'
require 'graphviz'
require 'webrick'
require 'fileutils'
module PuppetDebugger
module InputResponders
class Graph < InputResponderPlugin
COMMAND_WORDS = %w(graph)
SUMMARY = 'Graph out the catalog in GraphViz format'
COMMAND_GROUP = :tools
attr_accessor :status
def run(args = [])
toggle_status
end
def toggle_status
status = !status
if status
add_hook(:after_output, :create_graph_content) do |code, debugger|
# ensure we only start a single thread, otherwise they could stack up
# and try to write to the same file.
Thread.kill(@graph_thread) if @graph_thread
@graph_thread = Thread.new { create_html(create_graph_content) }
end
out = "Graph mode enabled at #{get_url}"
else
delete_hook(:after_output, :create_graph_content)
out = "Graph mode disabled"
end
out
end
def doc_root
File.expand_path '/tmp/puppet-debugger'
end
def get_url
server
'http://localhost:12000/'
end
def server
unless @server
@server = WEBrick::HTTPServer.new( {DocumentRoot: doc_root,
Logger: WEBrick::Log.new("/dev/null"), AccessLog: [],
Port: 12000} )
trap 'INT' do @server.shutdown end
Thread.new { @server.start }
end
@server
end
def create_graph_content
catalog = ::Puppet::Resource::Catalog.indirection.find(node.name, :use_node => node)
dotfile = catalog.to_ral.relationship_graph.to_dot
# SVG rendition of the graph
svg = ::GraphViz.parse_string(dotfile) do |graph|
graph[:label] = 'Resource Relationships'
# change the whits into something readable
graph.each_node do |name, node|
next unless name.start_with? 'Whit'
newname = name.dup
newname.sub!('Admissible_class', 'Starting Class')
newname.sub!('Completed_class', 'Finishing Class')
node[:style] = "filled",
node[:fillcolor] = :lightblue,
node[:label] = newname[5..-2]
end
end.output(:svg => String)
end
def create_html(svg_graph)
content = <<-EOF
<html>
<head>
<title>Relationship Graph</title>
<meta http-equiv="refresh" content="10">
</head>
<body>
<div class="relationships">#{svg_graph}</div>
</body>
</html>
EOF
FileUtils.mkdir_p(doc_root) unless File.exists?(doc_root)
File.write(File.join(doc_root, 'index.html'), content)
File.join(doc_root, 'index.html')
end
end
end
end
|
logicminds/puppet-debugger-graph
|
lib/debugger/graph.rb
|
require "debugger/graph/version"
module Debugger
module Graph
# Your code goes here...
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.