diff --git a/.standard.yml b/.standard.yml new file mode 100644 index 0000000..49bff5f --- /dev/null +++ b/.standard.yml @@ -0,0 +1 @@ +ruby_version: 3.3 diff --git a/Gemfile b/Gemfile index f13ddb9..3cf720c 100644 --- a/Gemfile +++ b/Gemfile @@ -1,12 +1,12 @@ source "https://rubygems.org" gemspec -if ENV['RAILS_VERSION'] - gem 'activesupport', ENV['RAILS_VERSION'] +if ENV["RAILS_VERSION"] + gem "activesupport", ENV["RAILS_VERSION"] end -if ENV['FARADAY_VERSION'] - gem 'faraday', ENV['FARADAY_VERSION'] +if ENV["FARADAY_VERSION"] + gem "faraday", ENV["FARADAY_VERSION"] end -gem 'debug' \ No newline at end of file +gem "debug" diff --git a/Rakefile b/Rakefile index 15d7c7b..1c238c1 100644 --- a/Rakefile +++ b/Rakefile @@ -1,12 +1,14 @@ #!/usr/bin/env rake require "bundler/gem_tasks" -require 'rspec/core/rake_task' +require "rspec/core/rake_task" +require "standard/rake" RSpec::Core::RakeTask.new(:spec) task :ci do - Rake::Task['spec'].invoke + Rake::Task["standard"].invoke + Rake::Task["spec"].invoke end task default: :ci diff --git a/bin/standardrb b/bin/standardrb new file mode 100755 index 0000000..3b77a15 --- /dev/null +++ b/bin/standardrb @@ -0,0 +1,16 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +# +# This file was generated by Bundler. +# +# The application 'standardrb' is installed as part of a gem, and +# this file is here to facilitate running it. +# + +ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../Gemfile", __dir__) + +require "rubygems" +require "bundler/setup" + +load Gem.bin_path("standard", "standardrb") diff --git a/iiif-presentation.gemspec b/iiif-presentation.gemspec index 23acd9e..7d7c179 100644 --- a/iiif-presentation.gemspec +++ b/iiif-presentation.gemspec @@ -1,29 +1,29 @@ -version = File.read(File.expand_path('../VERSION', __FILE__)).strip +version = File.read(File.expand_path("../VERSION", __FILE__)).strip Gem::Specification.new do |spec| - spec.name = 'iiif-presentation' - spec.version = version - spec.authors = ['Jon Stroop'] - spec.email = ['jpstroop@gmail.com'] - spec.description = 'API for working with IIIF Presentation manifests.' - spec.summary = 'API for working with IIIF Presentation manifests.' - spec.license = 'Simplified BSD' - spec.homepage = 'https://github.com/iiif/osullivan' + spec.name = "iiif-presentation" + spec.version = version + spec.authors = ["Jon Stroop"] + spec.email = ["jpstroop@gmail.com"] + spec.description = "API for working with IIIF Presentation manifests." + spec.summary = "API for working with IIIF Presentation manifests." + spec.license = "Simplified BSD" + spec.homepage = "https://github.com/iiif/osullivan" - spec.files = `git ls-files`.split($/) - spec.test_files = spec.files.grep(%r{^spec/}) - spec.require_paths = ['lib'] + spec.files = `git ls-files`.split($/) + spec.require_paths = ["lib"] - spec.add_development_dependency 'bundler' - spec.add_development_dependency 'rake' - spec.add_development_dependency 'rspec' - spec.add_development_dependency 'coveralls' - spec.add_development_dependency 'webmock' - spec.add_development_dependency 'multi_json' - spec.add_development_dependency 'vcr', '~> 6.4' + spec.add_development_dependency "bundler" + spec.add_development_dependency "rake" + spec.add_development_dependency "rspec" + spec.add_development_dependency "coveralls" + spec.add_development_dependency "webmock" + spec.add_development_dependency "multi_json" + spec.add_development_dependency "vcr", "~> 6.4" + spec.add_development_dependency "standard" - spec.add_dependency 'json' - spec.add_dependency 'activesupport', '>= 3.2.18' - spec.add_dependency 'faraday', '~> 2.7' - spec.add_dependency 'geo_coord' + spec.add_dependency "json" + spec.add_dependency "activesupport", ">= 3.2.18" + spec.add_dependency "faraday", "~> 2.7" + spec.add_dependency "geo_coord" end diff --git a/lib/iiif/hash_behaviours.rb b/lib/iiif/hash_behaviours.rb index eed724c..d99db7a 100644 --- a/lib/iiif/hash_behaviours.rb +++ b/lib/iiif/hash_behaviours.rb @@ -1,4 +1,4 @@ -require 'forwardable' +require "forwardable" module IIIF module HashBehaviours @@ -9,10 +9,9 @@ module HashBehaviours # * replace def_delegators :@data, :[], :[]=, :camelize_keys, :delete, :dig, :empty?, - :fetch, :has_key?, :has_value?, :include?, :insert, :insert_after, - :insert_before, :key, :key?, :keys, :length, :member?, :shift, :size, - :snakeize_keys, :store, :unshift, :value?, :values - + :fetch, :has_key?, :has_value?, :include?, :insert, :insert_after, + :insert_before, :key, :key?, :keys, :length, :member?, :shift, :size, + :snakeize_keys, :store, :unshift, :value?, :values ### # Methods that take a block and should return an instance (self or a new' @@ -23,11 +22,11 @@ module HashBehaviours SIMPLE_SELF_RETURNERS.each do |method_name| define_method(method_name) do |*arg, &block| - unless block.nil? # block_given? doesn't seem to work in this context - @data.send(method_name, *arg, &block) - return self - else + if block.nil? @data.send(method_name) + else # block_given? doesn't seem to work in this context + @data.send(method_name, *arg, &block) + self end end end @@ -35,7 +34,7 @@ module HashBehaviours # Clear is the only method that returns self but doesn't accept a block def clear @data.clear - return self + self end # Returns a new instance of this class containing the contents of' @@ -53,19 +52,19 @@ def clear # by calling the block with the key, its value in hsh and its value in' # another_obj. def merge another_obj - new_instance = self.class.new + new_instance = self.class.new # self.clone # Would this be better? What happens to other attributes of the class? if block_given? - self.each do |k,v| - if another_obj.has_key? k - new_instance[k] = yield(k, self[k], another_obj[k]) + each do |k, v| + new_instance[k] = if another_obj.has_key? k + yield(k, self[k], another_obj[k]) else - new_instance[k] = v + v end end else - self.each { |k,v| new_instance[k] = v } - another_obj.each { |k,v| new_instance[k] = v } + each { |k, v| new_instance[k] = v } + another_obj.each { |k, v| new_instance[k] = v } end new_instance end @@ -85,20 +84,20 @@ def merge another_obj # another_obj. def merge! another_obj if block_given? - self.each do |k,v| - if another_obj.has_key? k - self[k] = yield(k, self[k], another_obj[k]) + each do |k, v| + self[k] = if another_obj.has_key? k + yield(k, self[k], another_obj[k]) else - self[k] = v + v end end else - self.each { |k,v| self[k] = v } - another_obj.each { |k,v| self[k] = v } + each { |k, v| self[k] = v } + another_obj.each { |k, v| self[k] = v } end self end - alias update merge! + alias_method :update, :merge! # Deletes entries for which the supplied block evaluates to true. # Equivalent to #delete_if, but returns nil if there were no changes @@ -111,9 +110,9 @@ def reject! return_nil = false end end - return return_nil ? nil : self + return_nil ? nil : self else - return self.data.reject! + data.reject! end end @@ -123,9 +122,9 @@ def reject! def select new_instance = self.class.new if block_given? - @data.each { |k,v| new_instance.data[k] = v if yield(k,v) } + @data.each { |k, v| new_instance.data[k] = v if yield(k, v) } end - return new_instance + new_instance end # Deletes entries for which the supplied block evaluates to false. @@ -133,8 +132,8 @@ def select def select! if block_given? return_nil = true - @data.each do |k,v| - unless yield(k,v) + @data.each do |k, v| + unless yield(k, v) @data.delete(k) return_nil = false end @@ -143,8 +142,5 @@ def select! end self end - end - end - diff --git a/lib/iiif/ordered_hash.rb b/lib/iiif/ordered_hash.rb index ed637b9..48e9b28 100644 --- a/lib/iiif/ordered_hash.rb +++ b/lib/iiif/ordered_hash.rb @@ -1,8 +1,7 @@ -require 'active_support/inflector' +require "active_support/inflector" module IIIF class OrderedHash < ::Hash - # Insert a new key and value at the suppplied index. # # Note that this is slightly different from Array#insert in that new @@ -14,24 +13,24 @@ class OrderedHash < ::Hash # @param [Object] value def insert(index, key, value) tmp = IIIF::OrderedHash.new - index = self.length + 1 + index if index < 0 + index = length + 1 + index if index < 0 if index < 0 m = "Index #{index} is too small for current length (#{length})" raise IndexError, m end if index > 0 - i=0 - self.each do |k,v| + i = 0 + each do |k, v| tmp[k] = v - self.delete(k) - i+=1 + delete(k) + i += 1 break if i == index end end tmp[key] = value tmp.merge!(self) # copy the remaining to tmp - self.clear # start over... - self.merge!(tmp) # now put them all back + clear # start over... + merge!(tmp) # now put them all back self end @@ -49,9 +48,9 @@ def insert_before(hsh, &block) new_key = hsh[:new_key] value = hsh[:value] if block_given? - self.insert_here(0, new_key, value, &block) + insert_here(0, new_key, value, &block) else - self.insert_here(0, new_key, value, existing_key) + insert_here(0, new_key, value, existing_key) end end @@ -69,29 +68,29 @@ def insert_after(hsh, &block) new_key = hsh[:new_key] value = hsh[:value] if block_given? - self.insert_here(1, new_key, value, &block) + insert_here(1, new_key, value, &block) else - self.insert_here(1, new_key, value, existing_key) + insert_here(1, new_key, value, existing_key) end end # Delete any keys that are empty arrays def remove_empties - self.keys.each do |key| - if (self[key].kind_of?(Array) && self[key].empty?) || self[key].nil? - self.delete(key) + keys.each do |key| + if (self[key].is_a?(Array) && self[key].empty?) || self[key].nil? + delete(key) end end end # Covert snake_case keys to camelCase def camelize_keys - self.keys.each_with_index do |key, i| + keys.each_with_index do |key, i| camelized_key = key.camelize(:lower) if key != camelized_key - self.insert(i, camelized_key, self[key]) - self.delete(key) + insert(i, camelized_key, self[key]) + delete(key) end end self @@ -99,30 +98,30 @@ def camelize_keys # Covert camelCase keys to snake_case def snakeize_keys - self.keys.each_with_index do |key, i| + keys.each_with_index do |key, i| if key != key.underscore - self.insert(i, key.underscore, self[key]) - self.delete(key) + insert(i, key.underscore, self[key]) + delete(key) end end self end - # Prepends an entry to the front of the object. # Note that this is slightly different from Array#unshift in that new # entries must be added one at a time, i.e. unshift([k,v],[k,v],...) is # not currently supported. - def unshift k,v - self.insert(0, k, v) + def unshift k, v + insert(0, k, v) self end protected - def insert_here(where, new_key, value, existing_key=nil, &block) + + def insert_here(where, new_key, value, existing_key = nil, &block) idx = nil if block_given? - self.each_with_index do |(k,v), i| + each_with_index do |(k, v), i| if yield(k, v) idx = i break @@ -132,17 +131,16 @@ def insert_here(where, new_key, value, existing_key=nil, &block) raise KeyError, "Supplied block never evaluates to true" end else - unless self.has_key?(existing_key) + unless has_key?(existing_key) raise KeyError, "Existing key '#{existing_key}' does not exist" end - if self.has_key?(new_key) + if has_key?(new_key) raise KeyError, "Supplied new key '#{new_key}' already exists" end - idx = self.keys.index(existing_key) + where + idx = keys.index(existing_key) + where end - self.insert(idx, new_key, value) + insert(idx, new_key, value) self end - end end diff --git a/lib/iiif/presentation.rb b/lib/iiif/presentation.rb index 0b6870b..a425482 100644 --- a/lib/iiif/presentation.rb +++ b/lib/iiif/presentation.rb @@ -1,5 +1,5 @@ -require File.join(File.dirname(__FILE__), 'service') -%w{ +require File.join(File.dirname(__FILE__), "service") +%w[ abstract_resource annotation annotation_list @@ -8,19 +8,19 @@ layer manifest resource - image_resource + image_resource sequence service range -}.each do |f| - require File.join(File.dirname(__FILE__), 'presentation', f) +].each do |f| + require File.join(File.dirname(__FILE__), "presentation", f) end -require_relative 'ordered_hash' +require_relative "ordered_hash" module IIIF module Presentation - CONTEXT ||= 'http://iiif.io/api/presentation/2/context.json' + CONTEXT = "http://iiif.io/api/presentation/2/context.json" class MissingRequiredKeyError < StandardError; end class IllegalValueError < StandardError; end diff --git a/lib/iiif/presentation/abstract_resource.rb b/lib/iiif/presentation/abstract_resource.rb index 67f76f6..d137c02 100644 --- a/lib/iiif/presentation/abstract_resource.rb +++ b/lib/iiif/presentation/abstract_resource.rb @@ -1,44 +1,43 @@ -require File.join(File.dirname(__FILE__), '../service') +require File.join(File.dirname(__FILE__), "../service") module IIIF module Presentation class AbstractResource < Service - # Every subclass should override the following five methods where # appropriate, see Subclasses for how. def required_keys - %w{ @type } + %w[@type] end def any_type_keys # these are allowed on all classes - %w{ label description thumbnail attribution license logo see_also - related within } + %w[ label description thumbnail attribution license logo see_also + related within ] end def string_only_keys - %w{ viewing_hint } # should any of the any_type_keys be here? + %w[viewing_hint] # should any of the any_type_keys be here? end def array_only_keys - %w{ metadata } + %w[metadata] end def abstract_resource_only_keys - super + [ { key: 'service', type: IIIF::Service } ] + super + [{key: "service", type: IIIF::Service}] end def hash_only_keys - %w{ } + %w[] end def int_only_keys - %w{ } + %w[] end # Not every subclass is allowed to have viewingDirect, but when it is, # it must be one of these values def legal_viewing_direction_values - %w{ left-to-right right-to-left top-to-bottom bottom-to-top } + %w[left-to-right right-to-left top-to-bottom bottom-to-top] end def legal_viewing_hint_values @@ -49,30 +48,26 @@ def legal_viewing_hint_values # @param [Hash] hsh - Anything in this hash will be added to the Object. # @param [boolean] include_context (default: false). Pass true if the' # context should be included. - def initialize(hsh={}) - if self.class == IIIF::Presentation::AbstractResource + def initialize(hsh = {}) + if instance_of?(IIIF::Presentation::AbstractResource) raise "#{self.class} is an abstract class. Please use one of its subclasses." end - super(hsh) + super end - # Options: # * force: (true|false). Skips validations. # * include_context: (true|false). Adds the @context to the top of the # document if it doesn't exist. Default: true. # * sort_json_ld_keys: (true|false). Brings all properties starting with # '@'. Default: true. to the top of the document and sorts them. - def to_ordered_hash(opts={}) + def to_ordered_hash(opts = {}) include_context = opts.fetch(:include_context, true) - if include_context && !self.has_key?('@context') - self['@context'] = IIIF::Presentation::CONTEXT + if include_context && !has_key?("@context") + self["@context"] = IIIF::Presentation::CONTEXT end - super(opts) + super end - end - end end - diff --git a/lib/iiif/presentation/annotation.rb b/lib/iiif/presentation/annotation.rb index e218316..0fd8237 100644 --- a/lib/iiif/presentation/annotation.rb +++ b/lib/iiif/presentation/annotation.rb @@ -1,29 +1,27 @@ -require File.join(File.dirname(__FILE__), 'abstract_resource') +require File.join(File.dirname(__FILE__), "abstract_resource") module IIIF module Presentation class Annotation < AbstractResource - - TYPE = 'oa:Annotation' + TYPE = "oa:Annotation" def required_keys - super + %w{ motivation on } + super + %w[motivation on] end def string_only_keys - super + %w{ on } + super + %w[on] end def abstract_resource_only_keys - super + [ { key: 'resource', type: IIIF::Presentation::Resource } ] + super + [{key: "resource", type: IIIF::Presentation::Resource}] end - def initialize(hsh={}) - hsh['@type'] = TYPE unless hsh.has_key? '@type' - hsh['motivation'] = 'sc:painting' unless hsh.has_key? 'motivation' - super(hsh) + def initialize(hsh = {}) + hsh["@type"] = TYPE unless hsh.has_key? "@type" + hsh["motivation"] = "sc:painting" unless hsh.has_key? "motivation" + super end - end end end diff --git a/lib/iiif/presentation/annotation_list.rb b/lib/iiif/presentation/annotation_list.rb index ac780e9..c99c57e 100644 --- a/lib/iiif/presentation/annotation_list.rb +++ b/lib/iiif/presentation/annotation_list.rb @@ -1,28 +1,26 @@ -require File.join(File.dirname(__FILE__), 'abstract_resource') +require File.join(File.dirname(__FILE__), "abstract_resource") module IIIF module Presentation class AnnotationList < AbstractResource - - TYPE = 'sc:AnnotationList' + TYPE = "sc:AnnotationList" def required_keys - super + %w{ @id } + super + %w[@id] end - def array_only_keys; - super + %w{ resources }; + def array_only_keys + super + %w[resources] end - def initialize(hsh={}) - hsh['@type'] = TYPE unless hsh.has_key? '@type' - super(hsh) + def initialize(hsh = {}) + hsh["@type"] = TYPE unless hsh.has_key? "@type" + super end def validate # Each member or resources must be a kind of Annotation end - end end end diff --git a/lib/iiif/presentation/canvas.rb b/lib/iiif/presentation/canvas.rb index 5a3edbd..ec50ed5 100644 --- a/lib/iiif/presentation/canvas.rb +++ b/lib/iiif/presentation/canvas.rb @@ -1,41 +1,40 @@ -require File.join(File.dirname(__FILE__), 'abstract_resource') +require File.join(File.dirname(__FILE__), "abstract_resource") module IIIF module Presentation class Canvas < AbstractResource - # TODO (?) a simple 'Image Canvas' constructor. - TYPE = 'sc:Canvas' + TYPE = "sc:Canvas" def required_keys - super + %w{ @id width height label } + super + %w[@id width height label] end def any_type_keys - super + %w{ } + super + %w[] end def array_only_keys - super + %w{ images other_content } + super + %w[images other_content] end # TODO: test and validate def int_only_keys - super + %w{ width height } + super + %w[width height] end def numeric_only_keys - super + %w{ duration } + super + %w[duration] end def legal_viewing_hint_values - super + %w{ non-paged } + super + %w[non-paged] end - def initialize(hsh={}) - hsh['@type'] = TYPE unless hsh.has_key? '@type' - super(hsh) + def initialize(hsh = {}) + hsh["@type"] = TYPE unless hsh.has_key? "@type" + super end def validate @@ -43,7 +42,6 @@ def validate # all members of otherContent must be an annotation list super end - end end end diff --git a/lib/iiif/presentation/collection.rb b/lib/iiif/presentation/collection.rb index d515237..0ea84a1 100644 --- a/lib/iiif/presentation/collection.rb +++ b/lib/iiif/presentation/collection.rb @@ -1,29 +1,27 @@ -require File.join(File.dirname(__FILE__), 'abstract_resource') +require File.join(File.dirname(__FILE__), "abstract_resource") module IIIF module Presentation class Collection < AbstractResource - - TYPE = 'sc:Collection' + TYPE = "sc:Collection" def required_keys - super + %w{ @id label } + super + %w[@id label] end def array_only_keys - super + %w{ collections manifests } + super + %w[collections manifests] end - def initialize(hsh={}) - hsh['@type'] = TYPE unless hsh.has_key? '@type' - super(hsh) + def initialize(hsh = {}) + hsh["@type"] = TYPE unless hsh.has_key? "@type" + super end def validate # each member of collections and manifests must be a Hash # each member of collections and manifests MUST have @id, @type, and label end - end end end diff --git a/lib/iiif/presentation/image_resource.rb b/lib/iiif/presentation/image_resource.rb index 3559f26..26a0dba 100644 --- a/lib/iiif/presentation/image_resource.rb +++ b/lib/iiif/presentation/image_resource.rb @@ -1,44 +1,43 @@ -require File.join(File.dirname(__FILE__), 'resource') -require 'faraday' -require 'json' +require File.join(File.dirname(__FILE__), "resource") +require "faraday" +require "json" module IIIF module Presentation class ImageResource < Resource - - TYPE = 'dctypes:Image' + TYPE = "dctypes:Image" def int_only_keys - super + %w{ width height } + super + %w[width height] end - def initialize(hsh={}) - hsh['@type'] = TYPE unless hsh.has_key? '@type' - super(hsh) + def initialize(hsh = {}) + hsh["@type"] = TYPE unless hsh.has_key? "@type" + super end class << self - IMAGE_API_DEFAULT_PARAMS = '/full/!200,200/0/default.jpg' - IMAGE_API_CONTEXT = 'http://iiif.io/api/image/2/context.json' - DEFAULT_FORMAT = 'image/jpeg' + IMAGE_API_DEFAULT_PARAMS = "/full/!200,200/0/default.jpg" + IMAGE_API_CONTEXT = "http://iiif.io/api/image/2/context.json" + DEFAULT_FORMAT = "image/jpeg" # Create a new ImageResource that includes a IIIF Image API Service # See http://iiif.io/api/presentation/2.0/#image-resources # # Params - # * :service_id (required) - The base URI for the image on the image + # * :service_id (required) - The base URI for the image on the image # server. - # * :resource_id - The id for the resource; if supplied this should - # resolve to an actual image. Default: + # * :resource_id - The id for the resource; if supplied this should + # resolve to an actual image. Default: # "#{:service_id}/full/!200,200/0/default.jpg" - # * :format - The format of the image that is returned when + # * :format - The format of the image that is returned when # `:resource_id` is resolved. Default: 'image/jpeg' # * :height (Integer) # * :profile (String) - # * :width (Integer) - If width, height, and profile are not supplied, - # this method will try to get the info from the server (based on + # * :width (Integer) - If width, height, and profile are not supplied, + # this method will try to get the info from the server (based on # :resource_id) and raise an Exception if this is not possible for # some reason. - # * :copy_info (bool)- Even if width and height are supplied, try to + # * :copy_info (bool)- Even if width and height are supplied, try to # get the info.json from the server and copy it in. Default: false # # Raises: @@ -60,8 +59,7 @@ class << self # "width":1500 # } # - def create_image_api_image_resource(params={}) - + def create_image_api_image_resource(params = {}) service_id = params.fetch(:service_id) resource_id_default = "#{service_id}#{IMAGE_API_DEFAULT_PARAMS}" resource_id = params.fetch(:resource_id, resource_id_default) @@ -70,36 +68,37 @@ def create_image_api_image_resource(params={}) profile = params.fetch(:profile, nil) width = params.fetch(:width, nil) copy_info = params.fetch(:copy_info, false) - + have_whp = [width, height, profile].all? { |prop| !prop.nil? } remote_info = get_info(service_id) if !have_whp || copy_info - resource = self.new - resource['@id'] = resource_id + resource = new + resource["@id"] = resource_id resource.format = format - resource.width = width.nil? ? remote_info['width'] : width - resource.height = height.nil? ? remote_info['height'] : height + resource.width = width.nil? ? remote_info["width"] : width + resource.height = height.nil? ? remote_info["height"] : height resource.service = Service.new if copy_info resource.service.merge!(remote_info) else - resource.service['@context'] = IMAGE_API_CONTEXT - resource.service['@id'] = service_id - if profile.nil? - if remote_info['profile'].kind_of?(Array) - resource.service['profile'] = remote_info['profile'][0] + resource.service["@context"] = IMAGE_API_CONTEXT + resource.service["@id"] = service_id + resource.service["profile"] = if profile.nil? + if remote_info["profile"].is_a?(Array) + remote_info["profile"][0] else - resource.service['profile'] = remote_info['profile'] + remote_info["profile"] end else - resource.service['profile'] = profile + profile end end - return resource + resource end protected + def get_info(svc_id) conn = Faraday.new("#{svc_id}/info.json") do |c| c.use Faraday::Response::RaiseError @@ -114,7 +113,6 @@ def get_info(svc_id) JSON.parse(resp.body) end end - end end end diff --git a/lib/iiif/presentation/layer.rb b/lib/iiif/presentation/layer.rb index f881fc4..3409f3d 100644 --- a/lib/iiif/presentation/layer.rb +++ b/lib/iiif/presentation/layer.rb @@ -1,26 +1,25 @@ -require File.join(File.dirname(__FILE__), 'abstract_resource') +require File.join(File.dirname(__FILE__), "abstract_resource") module IIIF module Presentation class Layer < AbstractResource - - TYPE = 'sc:Layer' + TYPE = "sc:Layer" def required_keys - super + %w{ @id label } + super + %w[@id label] end def array_only_keys - super + %w{ other_content } + super + %w[other_content] end def string_only_keys - super + %w{ viewing_direction } # should any of the any_type_keys be here? + super + %w[viewing_direction] # should any of the any_type_keys be here? end - def initialize(hsh={}) - hsh['@type'] = TYPE unless hsh.has_key? '@type' - super(hsh) + def initialize(hsh = {}) + hsh["@type"] = TYPE unless hsh.has_key? "@type" + super end def validate @@ -28,7 +27,6 @@ def validate # can they be inline? super end - end end end diff --git a/lib/iiif/presentation/manifest.rb b/lib/iiif/presentation/manifest.rb index b6ae9c4..5bfd64c 100644 --- a/lib/iiif/presentation/manifest.rb +++ b/lib/iiif/presentation/manifest.rb @@ -1,30 +1,29 @@ -require File.join(File.dirname(__FILE__), 'abstract_resource') +require File.join(File.dirname(__FILE__), "abstract_resource") module IIIF module Presentation class Manifest < AbstractResource - - TYPE = 'sc:Manifest' + TYPE = "sc:Manifest" def required_keys - super + %w{ @id label } + super + %w[@id label] end def string_only_keys - super + %w{ viewing_direction } + super + %w[viewing_direction] end def array_only_keys - super + %w{ sequences structures } + super + %w[sequences structures] end def legal_viewing_hint_values - %w{ individuals paged continuous } + %w[individuals paged continuous] end - def initialize(hsh={}) - hsh['@type'] = TYPE unless hsh.has_key? '@type' - super(hsh) + def initialize(hsh = {}) + hsh["@type"] = TYPE unless hsh.has_key? "@type" + super end def validate @@ -32,8 +31,6 @@ def validate super end - end end end - diff --git a/lib/iiif/presentation/range.rb b/lib/iiif/presentation/range.rb index e438853..3b8f293 100644 --- a/lib/iiif/presentation/range.rb +++ b/lib/iiif/presentation/range.rb @@ -1,32 +1,30 @@ -require File.join(File.dirname(__FILE__), 'sequence') +require File.join(File.dirname(__FILE__), "sequence") module IIIF module Presentation class Range < Sequence - - TYPE = 'sc:Range' + TYPE = "sc:Range" def required_keys - super + %w{ @id label } + super + %w[@id label] end def array_only_keys - super + %w{ ranges } + super + %w[ranges] end def legal_viewing_hint_values - super + %w{ top } + super + %w[top] end - def initialize(hsh={}) - hsh['@type'] = TYPE unless hsh.has_key? '@type' - super(hsh) + def initialize(hsh = {}) + hsh["@type"] = TYPE unless hsh.has_key? "@type" + super end def validate # Values of the ranges array must be strings end - end end end diff --git a/lib/iiif/presentation/resource.rb b/lib/iiif/presentation/resource.rb index b0ec446..9fa8671 100644 --- a/lib/iiif/presentation/resource.rb +++ b/lib/iiif/presentation/resource.rb @@ -1,21 +1,19 @@ -require File.join(File.dirname(__FILE__), 'abstract_resource') +require File.join(File.dirname(__FILE__), "abstract_resource") module IIIF module Presentation class Resource < AbstractResource - def required_keys - %w{ @id } + %w[@id] end def string_only_keys - super + %w{ format } + super + %w[format] end - def initialize(hsh={}) - super(hsh) + def initialize(hsh = {}) + super end - end end end diff --git a/lib/iiif/presentation/sequence.rb b/lib/iiif/presentation/sequence.rb index e4145d6..7210a19 100644 --- a/lib/iiif/presentation/sequence.rb +++ b/lib/iiif/presentation/sequence.rb @@ -1,26 +1,25 @@ -require File.join(File.dirname(__FILE__), 'abstract_resource') +require File.join(File.dirname(__FILE__), "abstract_resource") module IIIF module Presentation class Sequence < AbstractResource - - TYPE = 'sc:Sequence' + TYPE = "sc:Sequence" def array_only_keys - super + %w{ canvases } + super + %w[canvases] end def string_only_keys - super + %w{ start_canvas viewing_direction } + super + %w[start_canvas viewing_direction] end def legal_viewing_hint_values - %w{ individuals paged continuous } + %w[individuals paged continuous] end - def initialize(hsh={}) - hsh['@type'] = TYPE unless hsh.has_key? '@type' - super(hsh) + def initialize(hsh = {}) + hsh["@type"] = TYPE unless hsh.has_key? "@type" + super end def validate @@ -28,8 +27,6 @@ def validate # * All members of canvases must be a kind of Canvas super end - end end end - diff --git a/lib/iiif/presentation/service.rb b/lib/iiif/presentation/service.rb index 7e8ada1..2ddd63c 100644 --- a/lib/iiif/presentation/service.rb +++ b/lib/iiif/presentation/service.rb @@ -1,4 +1,4 @@ -require File.join(File.dirname(__FILE__), 'abstract_resource') +require File.join(File.dirname(__FILE__), "abstract_resource") module IIIF module Presentation @@ -9,4 +9,3 @@ def required_keys end end end - diff --git a/lib/iiif/service.rb b/lib/iiif/service.rb index 81427c5..152f3f3 100644 --- a/lib/iiif/service.rb +++ b/lib/iiif/service.rb @@ -1,8 +1,8 @@ -require File.join(File.dirname(__FILE__), 'hash_behaviours') -require 'active_support/core_ext/class/subclasses' -require 'active_support/ordered_hash' -require 'active_support/inflector' -require 'json' +require File.join(File.dirname(__FILE__), "hash_behaviours") +require "active_support/core_ext/class/subclasses" +require "active_support/ordered_hash" +require "active_support/inflector" +require "json" module IIIF class Service @@ -10,24 +10,47 @@ class Service # Anything goes! SHOULD have @id and profile, MAY have label # Consider subclassing this for typical services... - def required_keys; %w{ }; end - def any_type_keys; %w{ }; end - def string_only_keys; %w{ }; end - def array_only_keys; %w{ }; end - def abstract_resource_only_keys; %w{ }; end - def hash_only_keys; %w{ }; end - def int_only_keys; %w{ }; end - def numeric_only_keys; %w{ }; end - - def initialize(hsh={}) + def required_keys + %w[] + end + + def any_type_keys + %w[] + end + + def string_only_keys + %w[] + end + + def array_only_keys + %w[] + end + + def abstract_resource_only_keys + %w[] + end + + def hash_only_keys + %w[] + end + + def int_only_keys + %w[] + end + + def numeric_only_keys + %w[] + end + + def initialize(hsh = {}) @data = IIIF::OrderedHash[hsh] - self.define_methods_for_any_type_keys - self.define_methods_for_array_only_keys - self.define_methods_for_string_only_keys - self.define_methods_for_int_only_keys - self.define_methods_for_numeric_only_keys - self.define_methods_for_abstract_resource_only_keys - self.snakeize_keys + define_methods_for_any_type_keys + define_methods_for_array_only_keys + define_methods_for_string_only_keys + define_methods_for_int_only_keys + define_methods_for_numeric_only_keys + define_methods_for_abstract_resource_only_keys + snakeize_keys end # Static methods / alternative constructors @@ -35,21 +58,21 @@ class << self # Parse from a file path, string, or existing hash def parse(s) ordered_hash = nil - if s.kind_of?(String) && File.exist?(s) + if s.is_a?(String) && File.exist?(s) ordered_hash = IIIF::OrderedHash[JSON.parse(IO.read(s))] - elsif s.kind_of?(String) && !File.exist?(s) + elsif s.is_a?(String) && !File.exist?(s) ordered_hash = IIIF::OrderedHash[JSON.parse(s)] - elsif s.kind_of?(Hash) + elsif s.is_a?(Hash) ordered_hash = IIIF::OrderedHash[s] else - m = '#parse takes a path to a file, a JSON String, or a Hash, ' + m = "#parse takes a path to a file, a JSON String, or a Hash, " m += "argument was a #{s.class}." - if s.kind_of?(String) - m+= "If you were trying to point to a file, does it exist?" + if s.is_a?(String) + m += "If you were trying to point to a file, does it exist?" end raise ArgumentError, m end - return IIIF::Service.from_ordered_hash(ordered_hash) + IIIF::Service.from_ordered_hash(ordered_hash) end end @@ -60,30 +83,30 @@ def validate # * type check String-only values # * type check Integer-only values # * type check AbstractResource-only values - self.required_keys.each do |k| - unless self.has_key?(k) + required_keys.each do |k| + unless has_key?(k) m = "A(n) #{k} is required for each #{self.class}" raise IIIF::Presentation::MissingRequiredKeyError, m end end # Viewing Direction values - if self.has_key?('viewing_direction') - unless self.legal_viewing_direction_values.include?(self['viewing_direction']) + if has_key?("viewing_direction") + unless legal_viewing_direction_values.include?(self["viewing_direction"]) m = "viewingDirection must be one of #{legal_viewing_direction_values}" raise IIIF::Presentation::IllegalValueError, m end end # Viewing Hint values - if self.has_key?('viewing_hint') - unless self.legal_viewing_hint_values.include?(self['viewing_hint']) - m = "viewingHint for #{self.class} must be one of #{self.legal_viewing_hint_values}." + if has_key?("viewing_hint") + unless legal_viewing_hint_values.include?(self["viewing_hint"]) + m = "viewingHint for #{self.class} must be one of #{legal_viewing_hint_values}." raise IIIF::Presentation::IllegalValueError, m end end # Metadata is all hashes - if self.has_key?('metadata') - unless self['metadata'].all? { |entry| entry.kind_of?(Hash) } - m = 'All entries in the metadata list must be a type of Hash' + if has_key?("metadata") + unless self["metadata"].all? { |entry| entry.is_a?(Hash) } + m = "All entries in the metadata list must be a type of Hash" raise IIIF::Presentation::IllegalValueError, m end end @@ -92,8 +115,8 @@ def validate # Options # * pretty: (true|false). Should the JSON be pretty-printed? (default: false) # * All options available in #to_ordered_hash - def to_json(opts={}) - hsh = self.to_ordered_hash(opts) + def to_json(opts = {}) + hsh = to_ordered_hash(opts) if opts.fetch(:pretty, false) JSON.pretty_generate(hsh) else @@ -105,19 +128,19 @@ def to_json(opts={}) # * force: (true|false). Skips validations. # * sort_json_ld_keys: (true|false). Brings all properties starting with # '@'. Default: true. to the top of the document and sorts them. - def to_ordered_hash(opts={}) + def to_ordered_hash(opts = {}) force = opts.fetch(:force, false) sort_json_ld_keys = opts.fetch(:sort_json_ld_keys, true) unless force - self.validate + validate end export_hash = IIIF::OrderedHash.new if sort_json_ld_keys - self.keys.select { |k| k.start_with?('@') }.sort!.each do |k| - export_hash[k] = self.data[k] + keys.select { |k| k.start_with?("@") }.sort!.each do |k| + export_hash[k] = data[k] end end @@ -126,25 +149,24 @@ def to_ordered_hash(opts={}) sort_json_ld_keys: sort_json_ld_keys, force: force } - self.keys.each do |k| - unless sort_json_ld_keys && k.start_with?('@') - if self.data[k].respond_to?(:to_ordered_hash) #.respond_to?(:to_ordered_hash) - export_hash[k] = self.data[k].to_ordered_hash(sub_opts) + keys.each do |k| + unless sort_json_ld_keys && k.start_with?("@") + if data[k].respond_to?(:to_ordered_hash) # .respond_to?(:to_ordered_hash) + export_hash[k] = data[k].to_ordered_hash(sub_opts) - elsif self.data[k].kind_of?(Hash) + elsif data[k].is_a?(Hash) export_hash[k] = IIIF::OrderedHash.new - self.data[k].each do |sub_k, v| - + data[k].each do |sub_k, v| if v.respond_to?(:to_ordered_hash) export_hash[k][sub_k] = v.to_ordered_hash(sub_opts) - elsif v.kind_of?(Array) + elsif v.is_a?(Array) export_hash[k][sub_k] = [] v.each do |member| - if member.respond_to?(:to_ordered_hash) - export_hash[k][sub_k] << member.to_ordered_hash(sub_opts) + export_hash[k][sub_k] << if member.respond_to?(:to_ordered_hash) + member.to_ordered_hash(sub_opts) else - export_hash[k][sub_k] << member + member end end else @@ -152,29 +174,28 @@ def to_ordered_hash(opts={}) end end - elsif self.data[k].kind_of?(Array) + elsif data[k].is_a?(Array) export_hash[k] = [] - self.data[k].each do |member| + data[k].each do |member| if member.respond_to?(:to_ordered_hash) export_hash[k] << member.to_ordered_hash(sub_opts) - elsif member.kind_of?(Hash) + elsif member.is_a?(Hash) hsh = IIIF::OrderedHash.new export_hash[k] << hsh - member.each do |sub_k,v| - + member.each do |sub_k, v| if v.respond_to?(:to_ordered_hash) hsh[sub_k] = v.to_ordered_hash(sub_opts) - elsif v.kind_of?(Array) + elsif v.is_a?(Array) hsh[sub_k] = [] v.each do |sub_member| - if sub_member.respond_to?(:to_ordered_hash) - hsh[sub_k] << sub_member.to_ordered_hash(sub_opts) + hsh[sub_k] << if sub_member.respond_to?(:to_ordered_hash) + sub_member.to_ordered_hash(sub_opts) else - hsh[sub_k] << sub_member + sub_member end end else @@ -188,7 +209,7 @@ def to_ordered_hash(opts={}) end end else - export_hash[k] = self.data[k] + export_hash[k] = data[k] end end @@ -198,35 +219,35 @@ def to_ordered_hash(opts={}) export_hash end - def self.from_ordered_hash(hsh, default_klass=IIIF::OrderedHash) + def self.from_ordered_hash(hsh, default_klass = IIIF::OrderedHash) # Create a new object (new_object) type = nil - if hsh.has_key?('@type') - type = IIIF::Service.get_descendant_class_by_jld_type(hsh['@type']) + if hsh.has_key?("@type") + type = IIIF::Service.get_descendant_class_by_jld_type(hsh["@type"]) end new_object = type.nil? ? default_klass.new : type.new hsh.keys.each do |key| - new_key = key.underscore == key ? key : key.underscore - if hsh[key].kind_of?(Array) + new_key = (key.underscore == key) ? key : key.underscore + if hsh[key].is_a?(Array) new_object[new_key] = [] hsh[key].each do |member| - if new_key == 'service' - new_object[new_key] << IIIF::Service.from_ordered_hash(member, IIIF::Presentation::Service) - elsif new_key == 'resource' - new_object[new_key] << IIIF::Service.from_ordered_hash(hsh[key], IIIF::Presentation::Resource) - elsif member.kind_of?(Hash) - new_object[new_key] << IIIF::Service.from_ordered_hash(member) + new_object[new_key] << if new_key == "service" + IIIF::Service.from_ordered_hash(member, IIIF::Presentation::Service) + elsif new_key == "resource" + IIIF::Service.from_ordered_hash(hsh[key], IIIF::Presentation::Resource) + elsif member.is_a?(Hash) + IIIF::Service.from_ordered_hash(member) else - new_object[new_key] << member + member # Again, no nested arrays, right? end end - elsif new_key == 'service' + elsif new_key == "service" new_object[new_key] = IIIF::Service.from_ordered_hash(hsh[key], IIIF::Presentation::Service) - elsif new_key == 'resource' + elsif new_key == "resource" new_object[new_key] = IIIF::Service.from_ordered_hash(hsh[key], IIIF::Presentation::Resource) - elsif hsh[key].kind_of?(Hash) + elsif hsh[key].is_a?(Hash) new_object[new_key] = IIIF::Service.from_ordered_hash(hsh[key]) else new_object[new_key] = hsh[key] @@ -235,8 +256,6 @@ def self.from_ordered_hash(hsh, default_klass=IIIF::OrderedHash) new_object end - protected - def self.get_descendant_class_by_jld_type(type) IIIF::Service.all_service_subclasses.find do |klass| klass.const_defined?(:TYPE) && klass.const_get(:TYPE) == type @@ -248,13 +267,11 @@ def self.all_service_subclasses @all_service_subclasses ||= IIIF::Service.descendants.reject(&:singleton_class?) end - def data=(hsh) - @data = hsh - end + protected - def data - @data - end + attr_writer :data + + attr_reader :data def define_methods_for_any_type_keys define_accessor_methods(*any_type_keys) @@ -263,14 +280,14 @@ def define_methods_for_any_type_keys # an array for empty values. any_type_keys.each do |key| define_singleton_method(key) do - self.send('[]', key) + send(:[], key) end end end def define_methods_for_array_only_keys define_accessor_methods(*array_only_keys) do |key, arg| - unless arg.kind_of?(Array) + unless arg.is_a?(Array) m = "#{key} must be an Array." raise IIIF::Presentation::IllegalValueError, m end @@ -284,7 +301,7 @@ def define_methods_for_abstract_resource_only_keys type = hsh[:type] define_accessor_methods(key) do |key, arg| - unless arg.kind_of?(type) + unless arg.is_a?(type) m = "#{key} must be an #{type}." raise IIIF::Presentation::IllegalValueError, m end @@ -294,7 +311,7 @@ def define_methods_for_abstract_resource_only_keys def define_methods_for_string_only_keys define_accessor_methods(*string_only_keys) do |key, arg| - unless arg.kind_of?(String) + unless arg.is_a?(String) m = "#{key} must be an String." raise IIIF::Presentation::IllegalValueError, m end @@ -303,7 +320,7 @@ def define_methods_for_string_only_keys def define_methods_for_int_only_keys define_accessor_methods(*int_only_keys) do |key, arg| - unless arg.kind_of?(Integer) && arg > 0 + unless arg.is_a?(Integer) && arg > 0 m = "#{key} must be a positive Integer." raise IIIF::Presentation::IllegalValueError, m end @@ -312,7 +329,7 @@ def define_methods_for_int_only_keys def define_methods_for_numeric_only_keys define_accessor_methods(*numeric_only_keys) do |key, arg| - unless arg.kind_of?(Numeric) && arg > 0 + unless arg.is_a?(Numeric) && arg > 0 m = "#{key} must be a positive Integer or Float." raise IIIF::Presentation::IllegalValueError, m end @@ -326,12 +343,12 @@ def define_accessor_methods(*keys, &validation) # Setter define_singleton_method("#{key}=") do |arg| validation.call(key, arg) if block_given? - self.send('[]=', key, arg) + send(:[]=, key, arg) end if camelized_key != key define_singleton_method("#{camelized_key}=") do |arg| validation.call(key, arg) if block_given? - self.send('[]=', key, arg) + send(:[]=, key, arg) end end # Getter @@ -341,7 +358,7 @@ def define_accessor_methods(*keys, &validation) end if camelized_key != key define_singleton_method(camelized_key) do - self.send('[]', key) + send(:[], key) end end end diff --git a/lib/iiif/v3/abstract_resource.rb b/lib/iiif/v3/abstract_resource.rb index 9b389cf..245c7bb 100644 --- a/lib/iiif/v3/abstract_resource.rb +++ b/lib/iiif/v3/abstract_resource.rb @@ -1,4 +1,4 @@ -require_relative '../hash_behaviours' +require_relative "../hash_behaviours" module IIIF module V3 @@ -6,19 +6,19 @@ class AbstractResource include IIIF::HashBehaviours # properties used by content resources only - CONTENT_RESOURCE_PROPERTIES = %w{ format height width duration } + CONTENT_RESOURCE_PROPERTIES = %w[format height width duration] # used by Collection, AnnotationCollection - PAGING_PROPERTIES = %w{ first last next prev total start_index } + PAGING_PROPERTIES = %w[first last next prev total start_index] # subclasses should override required_keys as appropriate, e.g. super + %w{ id } def required_keys - %w{ type } + %w[type] end # subclasses should override prohibited_keys as appropriate, e.g. super + PAGING_PROPERTIES def prohibited_keys - %w{ } + %w[] end # NOTE: keys associated with a single resource type are not included below in xxx_keys methods: @@ -27,37 +27,37 @@ def prohibited_keys def any_type_keys # values *may* be multivalued # NOTE: for id: "Resources that do not require URIs [for ids] may be assigned blank node identifiers" - %w{ id logo viewing_hint related see_also within } + %w[id logo viewing_hint related see_also within] end def string_only_keys - %w{ nav_date type format rights viewing_direction start_canvas } + %w[nav_date type format rights viewing_direction start_canvas] end def array_only_keys - %w{ metadata thumbnail rendering first last next prev items service } + %w[metadata thumbnail rendering first last next prev items service] end def hash_only_keys - %w{ label requiredStatement summary } + %w[label requiredStatement summary] end def int_only_keys - %w{ height width total start_index } + %w[height width total start_index] end def numeric_only_keys - %w{ duration } + %w[duration] end def uri_only_keys - %w{ } + %w[] end # Not every subclass is allowed to have viewingDirect, but when it is, # it must be one of these values def legal_viewing_direction_values - %w{ left-to-right right-to-left top-to-bottom bottom-to-top } + %w[left-to-right right-to-left top-to-bottom bottom-to-top] end def legal_viewing_hint_values @@ -69,19 +69,19 @@ def legal_viewing_hint_values # Order is only guaranteed if an ActiveSupport::OrderedHash is passed. # @param [boolean] include_context (default: false). Pass true if the # context should be included. - def initialize(hsh={}) - if self.class == IIIF::V3::AbstractResource + def initialize(hsh = {}) + if instance_of?(IIIF::V3::AbstractResource) raise "#{self.class} is an abstract class. Please use one of its subclasses." end @data = IIIF::OrderedHash[hsh] - self.define_methods_for_any_type_keys - self.define_methods_for_string_only_keys - self.define_methods_for_array_only_keys - self.define_methods_for_hash_only_keys - self.define_methods_for_int_only_keys - self.define_methods_for_numeric_only_keys - self.define_methods_for_uri_only_keys - self.snakeize_keys + define_methods_for_any_type_keys + define_methods_for_string_only_keys + define_methods_for_array_only_keys + define_methods_for_hash_only_keys + define_methods_for_int_only_keys + define_methods_for_numeric_only_keys + define_methods_for_uri_only_keys + snakeize_keys end # Static methods / alternative constructors @@ -89,34 +89,34 @@ class << self # Parse from a file path, string, or existing hash def parse(s) ordered_hash = nil - if s.kind_of?(String) && File.exist?(s) + if s.is_a?(String) && File.exist?(s) ordered_hash = IIIF::OrderedHash[JSON.parse(IO.read(s))] - elsif s.kind_of?(String) && !File.exist?(s) + elsif s.is_a?(String) && !File.exist?(s) ordered_hash = IIIF::OrderedHash[JSON.parse(s)] - elsif s.kind_of?(Hash) + elsif s.is_a?(Hash) ordered_hash = IIIF::OrderedHash[s] else - m = '#parse takes a path to a file, a JSON String, or a Hash, ' + m = "#parse takes a path to a file, a JSON String, or a Hash, " m += "argument was a #{s.class}." - if s.kind_of?(String) - m+= "If you were trying to point to a file, does it exist?" + if s.is_a?(String) + m += "If you were trying to point to a file, does it exist?" end raise ArgumentError, m end - return IIIF::V3::Presentation::Service.from_ordered_hash(ordered_hash) + IIIF::V3::Presentation::Service.from_ordered_hash(ordered_hash) end end def validate - self.required_keys.each do |k| - unless self.has_key?(k) + required_keys.each do |k| + unless has_key?(k) m = "A(n) #{k} is required for each #{self.class}" raise IIIF::V3::Presentation::MissingRequiredKeyError, m end end - self.prohibited_keys.each do |k| - if self.has_key?(k) + prohibited_keys.each do |k| + if has_key?(k) m = "#{k} is a prohibited key in #{self.class}" raise IIIF::V3::Presentation::ProhibitedKeyError, m end @@ -133,90 +133,91 @@ def validate # e.g. my_image_resource['format'] = 'image/jpeg' # Viewing Direction values - if self.has_key?('viewing_direction') - unless self.legal_viewing_direction_values.include?(self['viewing_direction']) + if has_key?("viewing_direction") + unless legal_viewing_direction_values.include?(self["viewing_direction"]) m = "viewingDirection must be one of #{legal_viewing_direction_values}" raise IIIF::V3::Presentation::IllegalValueError, m end end # Viewing Hint can be an Array ("Any resource type may have one or more viewing hints") - if self.has_key?('viewing_hint') - viewing_hint_val = self['viewing_hint'] + if has_key?("viewing_hint") + viewing_hint_val = self["viewing_hint"] [*viewing_hint_val].each { |vh_val| - unless self.legal_viewing_hint_values.include?(vh_val) || (vh_val.kind_of?(String) && vh_val =~ URI::regexp) - m = "viewingHint for #{self.class} must be one or more of #{self.legal_viewing_hint_values} or a URI" - raise IIIF::V3::Presentation::IllegalValueError, m + valid = legal_viewing_hint_values.include?(vh_val) || (vh_val.is_a?(String) && vh_val =~ URI::RFC2396_PARSER.make_regexp) + unless valid + m = "viewingHint for #{self.class} must be one or more of #{legal_viewing_hint_values} or a URI" + raise IIIF::V3::Presentation::IllegalValueError, m end } end # Metadata is Array; each entry is a Hash containing (only) 'label' and 'value' properties - if self.has_key?('metadata') && self['metadata'] - unless self['metadata'].all? { |entry| entry.kind_of?(Hash) } - m = 'metadata must be an Array with Hash members' + if has_key?("metadata") && self["metadata"] + unless self["metadata"].all? { |entry| entry.is_a?(Hash) } + m = "metadata must be an Array with Hash members" raise IIIF::V3::Presentation::IllegalValueError, m end - self['metadata'].each do |entry| + self["metadata"].each do |entry| md_keys = entry.keys - unless md_keys.size == 2 && md_keys.include?('label') && md_keys.include?('value') + unless md_keys.size == 2 && md_keys.include?("label") && md_keys.include?("value") m = "metadata members must be a Hash of keys 'label' and 'value'" raise IIIF::V3::Presentation::IllegalValueError, m end end end # Thumbnail is Array; each entry is a Hash or ImageResource containing (at least) 'id' and 'type' keys - if self.has_key?('thumbnail') && self['thumbnail'] - unless self['thumbnail'].all? { |entry| entry.kind_of?(IIIF::V3::Presentation::ImageResource) || entry.kind_of?(Hash) } - m = 'thumbnail must be an Array with Hash or ImageResource members' + if has_key?("thumbnail") && self["thumbnail"] + unless self["thumbnail"].all? { |entry| entry.is_a?(IIIF::V3::Presentation::ImageResource) || entry.is_a?(Hash) } + m = "thumbnail must be an Array with Hash or ImageResource members" raise IIIF::V3::Presentation::IllegalValueError, m end - self['thumbnail'].each do |entry| + self["thumbnail"].each do |entry| thumb_keys = entry.keys - unless thumb_keys.include?('id') && thumb_keys.include?('type') + unless thumb_keys.include?("id") && thumb_keys.include?("type") m = 'thumbnail members must include keys "id" and "type"' raise IIIF::V3::Presentation::IllegalValueError, m end end end # NavDate (navigation date) - if self.has_key?('nav_date') + if has_key?("nav_date") begin - Date.strptime(self['nav_date'], '%Y-%m-%dT%H:%M:%SZ') + Date.strptime(self["nav_date"], "%Y-%m-%dT%H:%M:%SZ") rescue ArgumentError m = "nav_date must be of form YYYY-MM-DDThh:mm:ssZ" raise IIIF::V3::Presentation::IllegalValueError, m end end - if key?('rights') && !self['rights'].kind_of?(String) - m = 'rights must be a String' + if key?("rights") && !self["rights"].is_a?(String) + m = "rights must be a String" raise IIIF::V3::Presentation::IllegalValueError, m end # rendering is Array; each entry is a Hash containing 'label' and 'format' keys - if self.has_key?('rendering') && self['rendering'] - unless self['rendering'].all? { |entry| entry.kind_of?(Hash) } - m = 'rendering must be an Array with Hash members' + if has_key?("rendering") && self["rendering"] + unless self["rendering"].all? { |entry| entry.is_a?(Hash) } + m = "rendering must be an Array with Hash members" raise IIIF::V3::Presentation::IllegalValueError, m end - self['rendering'].each do |entry| + self["rendering"].each do |entry| rendering_keys = entry.keys - unless rendering_keys.include?('label') && rendering_keys.include?('format') + unless rendering_keys.include?("label") && rendering_keys.include?("format") m = 'rendering members must be a Hash including keys "label" and "format"' raise IIIF::V3::Presentation::IllegalValueError, m end end end # startCanvas is a String with a URI value - if self.has_key?('start_canvas') && self['start_canvas'].kind_of?(String) - validate_uri(self['start_canvas'], 'startCanvas') # raises IllegalValueError + if has_key?("start_canvas") && self["start_canvas"].is_a?(String) + validate_uri(self["start_canvas"], "startCanvas") # raises IllegalValueError end end # Options # * pretty: (true|false). Should the JSON be pretty-printed? (default: false) # * All options available in #to_ordered_hash - def to_json(opts={}) - hsh = self.to_ordered_hash(opts) + def to_json(opts = {}) + hsh = to_ordered_hash(opts) if opts.fetch(:pretty, false) JSON.pretty_generate(hsh) else @@ -230,23 +231,23 @@ def to_json(opts={}) # document if it doesn't exist. Default: true. # * sort_json_ld_keys: (true|false). Brings all properties starting with # '@'. Default: true. to the top of the document and sorts them. - def to_ordered_hash(opts={}) + def to_ordered_hash(opts = {}) include_context = opts.fetch(:include_context, true) - if include_context && !self.has_key?('@context') - self['@context'] = IIIF::V3::Presentation::CONTEXT + if include_context && !has_key?("@context") + self["@context"] = IIIF::V3::Presentation::CONTEXT end force = opts.fetch(:force, false) sort_json_ld_keys = opts.fetch(:sort_json_ld_keys, true) unless force - self.validate + validate end export_hash = IIIF::OrderedHash.new if sort_json_ld_keys - self.keys.select { |k| k.start_with?('@') }.sort!.each do |k| - export_hash[k] = self.data[k] + keys.select { |k| k.start_with?("@") }.sort!.each do |k| + export_hash[k] = data[k] end end @@ -255,25 +256,24 @@ def to_ordered_hash(opts={}) sort_json_ld_keys: sort_json_ld_keys, force: force } - self.keys.each do |k| - unless sort_json_ld_keys && k.start_with?('@') - if self.data[k].respond_to?(:to_ordered_hash) #.respond_to?(:to_ordered_hash) - export_hash[k] = self.data[k].to_ordered_hash(sub_opts) + keys.each do |k| + unless sort_json_ld_keys && k.start_with?("@") + if data[k].respond_to?(:to_ordered_hash) # .respond_to?(:to_ordered_hash) + export_hash[k] = data[k].to_ordered_hash(sub_opts) - elsif self.data[k].kind_of?(Hash) + elsif data[k].is_a?(Hash) export_hash[k] = IIIF::OrderedHash.new - self.data[k].each do |sub_k, v| - + data[k].each do |sub_k, v| if v.respond_to?(:to_ordered_hash) export_hash[k][sub_k] = v.to_ordered_hash(sub_opts) - elsif v.kind_of?(Array) + elsif v.is_a?(Array) export_hash[k][sub_k] = [] v.each do |member| - if member.respond_to?(:to_ordered_hash) - export_hash[k][sub_k] << member.to_ordered_hash(sub_opts) + export_hash[k][sub_k] << if member.respond_to?(:to_ordered_hash) + member.to_ordered_hash(sub_opts) else - export_hash[k][sub_k] << member + member end end else @@ -281,29 +281,28 @@ def to_ordered_hash(opts={}) end end - elsif self.data[k].kind_of?(Array) + elsif data[k].is_a?(Array) export_hash[k] = [] - self.data[k].each do |member| + data[k].each do |member| if member.respond_to?(:to_ordered_hash) export_hash[k] << member.to_ordered_hash(sub_opts) - elsif member.kind_of?(Hash) + elsif member.is_a?(Hash) hsh = IIIF::OrderedHash.new export_hash[k] << hsh - member.each do |sub_k,v| - + member.each do |sub_k, v| if v.respond_to?(:to_ordered_hash) hsh[sub_k] = v.to_ordered_hash(sub_opts) - elsif v.kind_of?(Array) + elsif v.is_a?(Array) hsh[sub_k] = [] v.each do |sub_member| - if sub_member.respond_to?(:to_ordered_hash) - hsh[sub_k] << sub_member.to_ordered_hash(sub_opts) + hsh[sub_k] << if sub_member.respond_to?(:to_ordered_hash) + sub_member.to_ordered_hash(sub_opts) else - hsh[sub_k] << sub_member + sub_member end end else @@ -317,7 +316,7 @@ def to_ordered_hash(opts={}) end end else - export_hash[k] = self.data[k] + export_hash[k] = data[k] end end @@ -327,33 +326,33 @@ def to_ordered_hash(opts={}) export_hash end - def self.from_ordered_hash(hsh, default_klass=IIIF::OrderedHash) + def self.from_ordered_hash(hsh, default_klass = IIIF::OrderedHash) # Create a new object (new_object) type = nil - if hsh.has_key?('type') - type = IIIF::V3::AbstractResource.get_descendant_class_by_jld_type(hsh['type']) + if hsh.has_key?("type") + type = IIIF::V3::AbstractResource.get_descendant_class_by_jld_type(hsh["type"]) end new_object = type.nil? ? default_klass.new : type.new hsh.keys.each do |key| - new_key = key.underscore == key ? key : key.underscore - if new_key == 'service' + new_key = (key.underscore == key) ? key : key.underscore + if new_key == "service" new_object[new_key] = hsh[key].map do |entry| IIIF::V3::AbstractResource.from_ordered_hash(entry, IIIF::V3::Presentation::Service) end - elsif new_key == 'body' + elsif new_key == "body" new_object[new_key] = IIIF::V3::AbstractResource.from_ordered_hash(hsh[key], IIIF::V3::Presentation::Resource) - elsif hsh[key].kind_of?(Hash) + elsif hsh[key].is_a?(Hash) new_object[new_key] = IIIF::V3::AbstractResource.from_ordered_hash(hsh[key]) - elsif hsh[key].kind_of?(Array) + elsif hsh[key].is_a?(Array) new_object[new_key] = [] hsh[key].each do |member| - if new_key == 'service' - new_object[new_key] << IIIF::V3::AbstractResource.from_ordered_hash(member, IIIF::V3::Presentation::Service) - elsif member.kind_of?(Hash) - new_object[new_key] << IIIF::V3::AbstractResource.from_ordered_hash(member) + new_object[new_key] << if new_key == "service" + IIIF::V3::AbstractResource.from_ordered_hash(member, IIIF::V3::Presentation::Service) + elsif member.is_a?(Hash) + IIIF::V3::AbstractResource.from_ordered_hash(member) else - new_object[new_key] << member + member # Again, no nested arrays, right? end end @@ -364,8 +363,6 @@ def self.from_ordered_hash(hsh, default_klass=IIIF::OrderedHash) new_object end - protected - def self.get_descendant_class_by_jld_type(type) IIIF::V3::AbstractResource.all_known_subclasses.find do |klass| klass.const_defined?(:TYPE) && klass.const_get(:TYPE) == type @@ -376,13 +373,11 @@ def self.all_known_subclasses @all_known_subclasses ||= IIIF::V3::AbstractResource.descendants.reject(&:singleton_class?) end - def data=(hsh) - @data = hsh - end + protected - def data - @data - end + attr_writer :data + + attr_reader :data def define_methods_for_any_type_keys define_accessor_methods(*any_type_keys) @@ -391,14 +386,14 @@ def define_methods_for_any_type_keys # an array for empty values. any_type_keys.each do |key| define_singleton_method(key) do - self.send('[]', key) + send(:[], key) end end end def define_methods_for_array_only_keys define_accessor_methods(*array_only_keys) do |key, val| - unless val.kind_of?(Array) + unless val.is_a?(Array) m = "#{key} must be an Array." raise IIIF::V3::Presentation::IllegalValueError, m end @@ -407,7 +402,7 @@ def define_methods_for_array_only_keys def define_methods_for_hash_only_keys define_accessor_methods(*hash_only_keys) do |key, val| - unless val.kind_of?(Hash) + unless val.is_a?(Hash) m = "#{key} must be a Hash." raise IIIF::V3::Presentation::IllegalValueError, m end @@ -416,7 +411,7 @@ def define_methods_for_hash_only_keys def define_methods_for_string_only_keys define_accessor_methods(*string_only_keys) do |key, val| - unless val.kind_of?(String) + unless val.is_a?(String) m = "#{key} must be a String." raise IIIF::V3::Presentation::IllegalValueError, m end @@ -425,7 +420,7 @@ def define_methods_for_string_only_keys def define_methods_for_int_only_keys define_accessor_methods(*int_only_keys) do |key, val| - unless val.kind_of?(Integer) && val > 0 + unless val.is_a?(Integer) && val > 0 m = "#{key} must be a positive Integer." raise IIIF::V3::Presentation::IllegalValueError, m end @@ -434,7 +429,7 @@ def define_methods_for_int_only_keys def define_methods_for_numeric_only_keys define_accessor_methods(*numeric_only_keys) do |key, val| - unless val.kind_of?(Numeric) && val > 0 + unless val.is_a?(Numeric) && val > 0 m = "#{key} must be a positive Integer or Float." raise IIIF::V3::Presentation::IllegalValueError, m end @@ -452,12 +447,12 @@ def define_accessor_methods(*keys, &validation) # Setter define_singleton_method("#{key}=") do |val| validation.call(key, val) if block_given? - self.send('[]=', key, val) + send(:[]=, key, val) end if camelized_key != key define_singleton_method("#{camelized_key}=") do |val| validation.call(key, val) if block_given? - self.send('[]=', key, val) + send(:[]=, key, val) end end # Getter @@ -467,7 +462,7 @@ def define_accessor_methods(*keys, &validation) end if camelized_key != key define_singleton_method(camelized_key) do - self.send('[]', key) + send(:[], key) end end end @@ -481,7 +476,6 @@ def validate_uri(val, key) m = "#{key} value must be a String containing a URI for #{self.class}" raise IIIF::V3::Presentation::IllegalValueError, m end - end end end diff --git a/lib/iiif/v3/presentation.rb b/lib/iiif/v3/presentation.rb index 17a0a07..ae54359 100644 --- a/lib/iiif/v3/presentation.rb +++ b/lib/iiif/v3/presentation.rb @@ -1,9 +1,9 @@ -require_relative 'abstract_resource' -require_relative '../ordered_hash' +require_relative "abstract_resource" +require_relative "../ordered_hash" # NOTE: image_resource must follow resource due to inheritance # NOTE: range must follow sequence due to inheritance -%w{ +%w[ annotation annotation_collection annotation_page @@ -17,16 +17,16 @@ sequence range service -}.each do |f| - require File.join(File.dirname(__FILE__), 'presentation', f) +].each do |f| + require File.join(File.dirname(__FILE__), "presentation", f) end module IIIF module V3 module Presentation - CONTEXT ||= [ - 'http://www.w3.org/ns/anno.jsonld', - 'http://iiif.io/api/presentation/3/context.json' + CONTEXT = [ + "http://www.w3.org/ns/anno.jsonld", + "http://iiif.io/api/presentation/3/context.json" ] class MissingRequiredKeyError < StandardError; end diff --git a/lib/iiif/v3/presentation/annotation.rb b/lib/iiif/v3/presentation/annotation.rb index 0d1e76f..f706b2d 100644 --- a/lib/iiif/v3/presentation/annotation.rb +++ b/lib/iiif/v3/presentation/annotation.rb @@ -2,68 +2,67 @@ module IIIF module V3 module Presentation class Annotation < IIIF::V3::AbstractResource - - TYPE = 'Annotation'.freeze + TYPE = "Annotation".freeze def required_keys - super + %w{ id motivation target } + super + %w[id motivation target] end def prohibited_keys super + CONTENT_RESOURCE_PROPERTIES + PAGING_PROPERTIES + - %w{ nav_date viewing_direction start_canvas content_annotations } + %w[nav_date viewing_direction start_canvas content_annotations] end def any_type_keys - super + %w{ body target } + super + %w[body target] end def uri_only_keys - super + %w{ id } + super + %w[id] end def string_only_keys - super + %w{ motivation time_mode } + super + %w[motivation time_mode] end def legal_time_mode_values - %w{ trim scale loop }.freeze + %w[trim scale loop].freeze end def legal_viewing_hint_values - super + %w{ none } + super + %w[none] end - def initialize(hsh={}) - hsh['type'] = TYPE unless hsh.has_key? 'type' - hsh['motivation'] = 'painting' unless hsh.has_key? 'motivation' - super(hsh) + def initialize(hsh = {}) + hsh["type"] = TYPE unless hsh.has_key? "type" + hsh["motivation"] = "painting" unless hsh.has_key? "motivation" + super end def validate super - if self.has_key?('body') && self['body'].kind_of?(IIIF::V3::Presentation::ImageResource) + if has_key?("body") && self["body"].is_a?(IIIF::V3::Presentation::ImageResource) img_res_class_str = "IIIF::V3::Presentation::ImageResource" - unless self.motivation == 'painting' + unless motivation == "painting" m = "#{self.class} motivation must be 'painting' when body is a kind of #{img_res_class_str}" raise IIIF::V3::Presentation::IllegalValueError, m end - body_resource = self['body'] - body_id = body_resource['id'] + body_resource = self["body"] + body_id = body_resource["id"] if body_id && body_id =~ /^https?:/ - validate_uri(body_id, 'anno body ImageResource id') # can raise IllegalValueError + validate_uri(body_id, "anno body ImageResource id") # can raise IllegalValueError else m = "when #{self.class} body is a kind of #{img_res_class_str}, ImageResource id must be an http(s) URI" raise IIIF::V3::Presentation::IllegalValueError, m end end - if self.has_key?('time_mode') - unless self.legal_time_mode_values.include?(self['time_mode']) - m = "timeMode for #{self.class} must be one of #{self.legal_time_mode_values}." + if has_key?("time_mode") + unless legal_time_mode_values.include?(self["time_mode"]) + m = "timeMode for #{self.class} must be one of #{legal_time_mode_values}." raise IIIF::V3::Presentation::IllegalValueError, m end end diff --git a/lib/iiif/v3/presentation/annotation_collection.rb b/lib/iiif/v3/presentation/annotation_collection.rb index 469c9fa..06511ad 100644 --- a/lib/iiif/v3/presentation/annotation_collection.rb +++ b/lib/iiif/v3/presentation/annotation_collection.rb @@ -2,19 +2,18 @@ module IIIF module V3 module Presentation class AnnotationCollection < IIIF::V3::AbstractResource - - TYPE = 'AnnotationCollection'.freeze + TYPE = "AnnotationCollection".freeze def required_keys - super + %w{ id } + super + %w[id] end def int_only_keys - super + %w{ total } + super + %w[total] end def array_only_keys - super + %w{ content } + super + %w[content] end # TODO: paging properties @@ -27,11 +26,10 @@ def array_only_keys # # don't forget to validate - def initialize(hsh={}) - hsh['type'] = TYPE unless hsh.has_key? 'type' - super(hsh) + def initialize(hsh = {}) + hsh["type"] = TYPE unless hsh.has_key? "type" + super end - end end end diff --git a/lib/iiif/v3/presentation/annotation_page.rb b/lib/iiif/v3/presentation/annotation_page.rb index 07c29a3..bce757b 100644 --- a/lib/iiif/v3/presentation/annotation_page.rb +++ b/lib/iiif/v3/presentation/annotation_page.rb @@ -2,47 +2,46 @@ module IIIF module V3 module Presentation class AnnotationPage < IIIF::V3::AbstractResource - - TYPE = 'AnnotationPage'.freeze + TYPE = "AnnotationPage".freeze def required_keys - super + %w{ id } + super + %w[id] end def prohibited_keys super + CONTENT_RESOURCE_PROPERTIES + - %w{ first last total nav_date viewing_direction start_canvas content_annotations } + %w[first last total nav_date viewing_direction start_canvas content_annotations] end def uri_only_keys - super + %w{ id } + super + %w[id] end - def array_only_keys; - super + %w{ items } + def array_only_keys + super + %w[items] end def legal_viewing_hint_values - super + %w{ none } + super + %w[none] end - def initialize(hsh={}) - hsh['type'] = TYPE unless hsh.has_key? 'type' - super(hsh) + def initialize(hsh = {}) + hsh["type"] = TYPE unless hsh.has_key? "type" + super end def validate super - unless self['id'] =~ /^https?:/ + unless /^https?:/.match?(self["id"]) err_msg = "id must be an http(s) URI for #{self.class}" raise IIIF::V3::Presentation::IllegalValueError, err_msg end - items = self['items'] - if items && items.any? + items = self["items"] + if items&.any? unless items.all? { |entry| entry.instance_of?(IIIF::V3::Presentation::Annotation) } - err_msg = 'All entries in the items list must be a IIIF::V3::Presentation::Annotation' + err_msg = "All entries in the items list must be a IIIF::V3::Presentation::Annotation" raise IIIF::V3::Presentation::IllegalValueError, err_msg end end diff --git a/lib/iiif/v3/presentation/canvas.rb b/lib/iiif/v3/presentation/canvas.rb index e0d1760..580e340 100644 --- a/lib/iiif/v3/presentation/canvas.rb +++ b/lib/iiif/v3/presentation/canvas.rb @@ -2,54 +2,53 @@ module IIIF module V3 module Presentation class Canvas < IIIF::V3::AbstractResource - - TYPE = 'Canvas'.freeze + TYPE = "Canvas".freeze def required_keys - super + %w{ id label } + super + %w[id label] end def prohibited_keys - super + PAGING_PROPERTIES + %w{ viewing_direction format nav_date start_canvas content_annotations } + super + PAGING_PROPERTIES + %w[viewing_direction format nav_date start_canvas content_annotations] end def int_only_keys - super + %w{ depth } + super + %w[depth] end def array_only_keys - super + %w{ content } + super + %w[content] end def legal_viewing_hint_values - super + %w{ paged continuous non-paged facing-pages auto-advance } + super + %w[paged continuous non-paged facing-pages auto-advance] end - def initialize(hsh={}) - hsh['type'] = TYPE unless hsh.has_key? 'type' - super(hsh) + def initialize(hsh = {}) + hsh["type"] = TYPE unless hsh.has_key? "type" + super end def validate super - id_uri = URI.parse(self['id']) - unless self['id'] =~ /^https?:/ && id_uri.fragment.nil? + id_uri = URI.parse(self["id"]) + unless self["id"] =~ /^https?:/ && id_uri.fragment.nil? err_msg = "id must be an http(s) URI without a fragment for #{self.class}" raise IIIF::V3::Presentation::IllegalValueError, err_msg end - content = self['content'] - if content && content.any? + content = self["content"] + if content&.any? unless content.all? { |entry| entry.instance_of?(IIIF::V3::Presentation::AnnotationPage) } - err_msg = 'All entries in the content list must be a IIIF::V3::Presentation::AnnotationPage' + err_msg = "All entries in the content list must be a IIIF::V3::Presentation::AnnotationPage" raise IIIF::V3::Presentation::IllegalValueError, err_msg end content.each do |anno_page| - annos = anno_page['items'] - if annos && annos.any? - unless annos.all? { |anno| anno.target == self.id } - err_msg = 'URI of the canvas must be repeated in the target field of included Annotations' + annos = anno_page["items"] + if annos&.any? + unless annos.all? { |anno| anno.target == id } + err_msg = "URI of the canvas must be repeated in the target field of included Annotations" raise IIIF::V3::Presentation::IllegalValueError, err_msg end end @@ -58,9 +57,9 @@ def validate # "A canvas MUST have exactly one width and one height, or exactly one duration. # It may have width, height and duration."" - height = self['height'] - width = self['width'] - if (!!height ^ !!width) # this is an exclusive or: forces height and width to boolean + height = self["height"] + width = self["width"] + if !!height ^ !!width # this is an exclusive or: forces height and width to boolean extent_err_msg = "#{self.class} requires both height and width or neither" raise IIIF::V3::Presentation::IllegalValueError, extent_err_msg end diff --git a/lib/iiif/v3/presentation/choice.rb b/lib/iiif/v3/presentation/choice.rb index 092477d..a6e6b05 100644 --- a/lib/iiif/v3/presentation/choice.rb +++ b/lib/iiif/v3/presentation/choice.rb @@ -2,45 +2,44 @@ module IIIF module V3 module Presentation class Choice < IIIF::V3::AbstractResource - - TYPE = 'Choice'.freeze + TYPE = "Choice".freeze def prohibited_keys super + CONTENT_RESOURCE_PROPERTIES + PAGING_PROPERTIES + - %w{ nav_date viewing_direction start_canvas content_annotations } + %w[nav_date viewing_direction start_canvas content_annotations] end def any_type_keys - super + %w{ default } + super + %w[default] end def string_only_keys - super + %w{ choice_hint } + super + %w[choice_hint] end - def array_only_keys; - super + %w{ items }; + def array_only_keys + super + %w[items] end def legal_viewing_hint_values - %w{ none } + %w[none] end def legal_choice_hint_values - %w{ client user } + %w[client user] end - def initialize(hsh={}) - hsh['type'] = TYPE unless hsh.has_key? 'type' - super(hsh) + def initialize(hsh = {}) + hsh["type"] = TYPE unless hsh.has_key? "type" + super end def validate super - if self.has_key?('choice_hint') - unless self.legal_choice_hint_values.include?(self['choice_hint']) - m = "choiceHint for #{self.class} must be one of #{self.legal_choice_hint_values}." + if has_key?("choice_hint") + unless legal_choice_hint_values.include?(self["choice_hint"]) + m = "choiceHint for #{self.class} must be one of #{legal_choice_hint_values}." raise IIIF::V3::Presentation::IllegalValueError, m end end diff --git a/lib/iiif/v3/presentation/collection.rb b/lib/iiif/v3/presentation/collection.rb index 76f4f89..687065a 100644 --- a/lib/iiif/v3/presentation/collection.rb +++ b/lib/iiif/v3/presentation/collection.rb @@ -2,15 +2,14 @@ module IIIF module V3 module Presentation class Collection < IIIF::V3::AbstractResource - - TYPE = 'Collection'.freeze + TYPE = "Collection".freeze def required_keys - super + %w{ id label } + super + %w[id label] end def array_only_keys - super + %w{ collections manifests } + super + %w[collections manifests] end # TODO: navDate (collection or manifest only) - The value must be an xsd:dateTime literal in UTC, expressed in the form “YYYY-MM-DDThh:mm:ssZ”; There must be at most one navDate associated with any given resource. @@ -24,12 +23,12 @@ def array_only_keys # The value must be a non-negative integer. def legal_viewing_hint_values - %w{ auto-advance together } + %w[auto-advance together] end - def initialize(hsh={}) - hsh['type'] = TYPE unless hsh.has_key? 'type' - super(hsh) + def initialize(hsh = {}) + hsh["type"] = TYPE unless hsh.has_key? "type" + super end def validate diff --git a/lib/iiif/v3/presentation/image_resource.rb b/lib/iiif/v3/presentation/image_resource.rb index 4337bcf..3b018c0 100644 --- a/lib/iiif/v3/presentation/image_resource.rb +++ b/lib/iiif/v3/presentation/image_resource.rb @@ -1,20 +1,19 @@ -require 'faraday' +require "faraday" module IIIF module V3 module Presentation class ImageResource < Resource + TYPE = "Image".freeze - TYPE = 'Image'.freeze - - def initialize(hsh={}) - hsh['type'] = TYPE unless hsh.has_key? 'type' - super(hsh) + def initialize(hsh = {}) + hsh["type"] = TYPE unless hsh.has_key? "type" + super end class << self - IMAGE_API_DEFAULT_PARAMS = '/full/!200,200/0/default.jpg'.freeze - DEFAULT_FORMAT = 'image/jpeg'.freeze + IMAGE_API_DEFAULT_PARAMS = "/full/!200,200/0/default.jpg".freeze + DEFAULT_FORMAT = "image/jpeg".freeze # Create a new ImageResource that includes a IIIF Image API Service # See http://iiif.io/api/presentation/2.0/#image-resources # @@ -54,8 +53,7 @@ class << self # "width":1500 # } # - def create_image_api_image_resource(params={}) - + def create_image_api_image_resource(params = {}) service_id = params.fetch(:service_id) resource_id_default = "#{service_id}#{IMAGE_API_DEFAULT_PARAMS}" resource_id = params.fetch(:resource_id, resource_id_default) @@ -69,32 +67,33 @@ def create_image_api_image_resource(params={}) remote_info = get_info(service_id) if !have_whp || copy_info - resource = self.new - resource['id'] = resource_id + resource = new + resource["id"] = resource_id resource.format = format - resource.width = width.nil? ? remote_info['width'] : width - resource.height = height.nil? ? remote_info['height'] : height + resource.width = width.nil? ? remote_info["width"] : width + resource.height = height.nil? ? remote_info["height"] : height resource_service = Service.new if copy_info resource_service.merge!(remote_info) - resource_service['id'] ||= resource_service.delete('@id') + resource_service["id"] ||= resource_service.delete("@id") else - resource_service['id'] = service_id - if profile.nil? - if remote_info['profile'].kind_of?(Array) - resource_service['profile'] = remote_info['profile'][0] + resource_service["id"] = service_id + resource_service["profile"] = if profile.nil? + if remote_info["profile"].is_a?(Array) + remote_info["profile"][0] else - resource_service['profile'] = remote_info['profile'] + remote_info["profile"] end else - resource_service['profile'] = profile + profile end end resource.service = [resource_service] - return resource + resource end protected + def get_info(svc_id) conn = Faraday.new("#{svc_id}/info.json") do |c| c.use Faraday::Response::RaiseError diff --git a/lib/iiif/v3/presentation/manifest.rb b/lib/iiif/v3/presentation/manifest.rb index 8e76d7c..3082e4f 100644 --- a/lib/iiif/v3/presentation/manifest.rb +++ b/lib/iiif/v3/presentation/manifest.rb @@ -2,62 +2,61 @@ module IIIF module V3 module Presentation class Manifest < IIIF::V3::AbstractResource - - TYPE = 'Manifest'.freeze + TYPE = "Manifest".freeze def required_keys # NOTE: relaxing requirement for items as Universal Viewer currently only accepts sequences # see https://github.com/sul-dlss/osullivan/issues/27, sul-dlss/purl/issues/167 # super + %w{ id label items } - super + %w{ id label } + super + %w[id label] end def prohibited_keys - super + CONTENT_RESOURCE_PROPERTIES + PAGING_PROPERTIES + %w{ start_canvas content_annotation } + super + CONTENT_RESOURCE_PROPERTIES + PAGING_PROPERTIES + %w[start_canvas content_annotation] end def uri_only_keys - super + %w{ id } + super + %w[id] end def array_only_keys # NOTE: allowing 'items' or 'sequences' as Universal Viewer currently only accepts sequences # see https://github.com/sul-dlss/osullivan/issues/27, sul-dlss/purl/issues/167 # super + %w{ items structures } - super + %w{ items structures sequences } + super + %w[items structures sequences] end def legal_viewing_hint_values - %w{ individuals paged continuous auto-advance } + %w[individuals paged continuous auto-advance] end - def initialize(hsh={}) - hsh['type'] = TYPE unless hsh.has_key? 'type' - super(hsh) + def initialize(hsh = {}) + hsh["type"] = TYPE unless hsh.has_key? "type" + super end def validate super # also checks navDate format - unless self['id'] =~ /^https?:/ + unless /^https?:/.match?(self["id"]) err_msg = "id must be an http(s) URI for #{self.class}" raise IIIF::V3::Presentation::IllegalValueError, err_msg end # Items object list - unless self&.[]('items')&.any? - m = 'The items list must have at least one entry (and it must be a IIIF::V3::Presentation::Canvas)' + unless self&.[]("items")&.any? + m = "The items list must have at least one entry (and it must be a IIIF::V3::Presentation::Canvas)" raise IIIF::V3::Presentation::MissingRequiredKeyError, m end - validate_items_list(self['items']) if self['items'] + validate_items_list(self["items"]) if self["items"] # TODO: when embedding a sequence without any extensions within a manifest, the sequence must not have the @context field. # TODO: AnnotationLists must not be embedded within the manifest - if self['structures'] - unless self['structures'].all? { |entry| entry.instance_of?(IIIF::V3::Presentation::Range)} - m = 'All entries in the structures list must be a IIIF::V3::Presentation::Range' + if self["structures"] + unless self["structures"].all? { |entry| entry.instance_of?(IIIF::V3::Presentation::Range) } + m = "All entries in the structures list must be a IIIF::V3::Presentation::Range" raise IIIF::V3::Presentation::IllegalValueError, m end end @@ -65,12 +64,12 @@ def validate def validate_items_list(items_array) unless items_array.size >= 1 - m = 'The items list must have at least one entry (and it must be a IIIF::V3::Presentation::Canvas)' + m = "The items list must have at least one entry (and it must be a IIIF::V3::Presentation::Canvas)" raise IIIF::V3::Presentation::MissingRequiredKeyError, m end unless items_array.all? { |entry| entry.instance_of?(IIIF::V3::Presentation::Canvas) } - m = 'All entries in the items list must be a IIIF::V3::Presentation::Canvas' + m = "All entries in the items list must be a IIIF::V3::Presentation::Canvas" raise IIIF::V3::Presentation::IllegalValueError, m end end diff --git a/lib/iiif/v3/presentation/nav_place.rb b/lib/iiif/v3/presentation/nav_place.rb index 023ebe1..b9decc2 100644 --- a/lib/iiif/v3/presentation/nav_place.rb +++ b/lib/iiif/v3/presentation/nav_place.rb @@ -1,6 +1,6 @@ -require 'geo/coord' -require 'json' -require 'uri' +require "geo/coord" +require "json" +require "uri" module IIIF module V3 @@ -18,11 +18,11 @@ class NavPlace < IIIF::V3::AbstractResource # ("E 138.0"). COORD_REGEX = / (?:(?[NSEW])\s*)?(?#{DECIMAL})[°⁰*] - (?:\s*(?#{DECIMAL})[\'ʹ′])? + (?:\s*(?#{DECIMAL})['ʹ′])? (?:\s*(?#{DECIMAL})["ʺ″])? (?:\s*(?[NSEW]))? | - (?[NSEW])\s*(?\d+\.\d+)(?![\d.°⁰*\'ʹ′"ʺ″]) + (?[NSEW])\s*(?\d+\.\d+)(?![\d.°⁰*'ʹ′"ʺ″]) /x # WKT versions of points and boxes (polygon/multipolygon). @@ -47,11 +47,11 @@ def valid? end def build - raise ArgumentError.new('invalid coordinates') unless valid? + raise ArgumentError.new("invalid coordinates") unless valid? with_id("#{base_uri}/feature-collection/1", - type: 'FeatureCollection', - features: features) + type: "FeatureCollection", + features: features) end private @@ -78,7 +78,7 @@ def coord_for(long_str, lat_str) return unless long_matcher && lat_matcher Geo::Coord.new(latd: lat_matcher[:degrees], latm: lat_matcher[:minutes], lats: lat_matcher[:seconds], lath: lat_matcher[:hemisphere], - lngd: long_matcher[:degrees], lngm: long_matcher[:minutes], lngs: long_matcher[:seconds], lngh: long_matcher[:hemisphere]) + lngd: long_matcher[:degrees], lngm: long_matcher[:minutes], lngs: long_matcher[:seconds], lngh: long_matcher[:hemisphere]) rescue ArgumentError nil end @@ -95,16 +95,16 @@ def rect_for(coordinate_parts) # @return [Hash, nil] the GeoJSON geometry, or nil if the WKT isn't one we can use def wkt_geometry(text) match = text.match(WKT_REGEX) - body = match[:body].gsub(/(#{WKT_NUMBER})\s+(#{WKT_NUMBER})/) { "[#{Float($1).round(6)},#{Float($2).round(6)}]" } - coordinates = JSON.parse(body.tr('()', '[]')) + body = match[:body].gsub(/(#{WKT_NUMBER})\s+(#{WKT_NUMBER})/o) { "[#{Float($1).round(6)},#{Float($2).round(6)}]" } + coordinates = JSON.parse(body.tr("()", "[]")) case match[:type].upcase - when 'POINT' - { type: 'Point', coordinates: coordinates.first } if coordinates.length == 1 && point?(coordinates.first) - when 'POLYGON' - { type: 'Polygon', coordinates: oriented(coordinates) } if polygon?(coordinates) - when 'MULTIPOLYGON' - { type: 'MultiPolygon', coordinates: coordinates.map { |polygon| oriented(polygon) } } if coordinates.any? && coordinates.all? { |polygon| polygon?(polygon) } + when "POINT" + {type: "Point", coordinates: coordinates.first} if coordinates.length == 1 && point?(coordinates.first) + when "POLYGON" + {type: "Polygon", coordinates: oriented(coordinates)} if polygon?(coordinates) + when "MULTIPOLYGON" + {type: "MultiPolygon", coordinates: coordinates.map { |polygon| oriented(polygon) }} if coordinates.any? && coordinates.all? { |polygon| polygon?(polygon) } end rescue JSON::ParserError, ArgumentError nil @@ -125,16 +125,16 @@ def polygon?(value) def oriented(polygon) polygon.each_with_index.map do |ring, index| area = ring.each_cons(2).sum { |(x1, y1), (x2, y2)| x1 * y2 - x2 * y1 } - (area > 0) == index.zero? ? ring : ring.reverse + ((area > 0) == index.zero?) ? ring : ring.reverse end end def features coordinates.map.with_index(1) do |coordinate, index| with_id("#{base_uri}/iiif/feature/#{index}", - type: 'Feature', - properties: {}, - geometry: geometry_for(coordinate)) + type: "Feature", + properties: {}, + geometry: geometry_for(coordinate)) end end @@ -148,12 +148,12 @@ def geometry_for(coordinate) # The navPlace extension makes ids optional, so leave them out without a base_uri. def with_id(id, resource) - base_uri ? { id: id }.merge(resource) : resource + base_uri ? {id: id}.merge(resource) : resource end def point_geometry(coord) { - type: 'Point', + type: "Point", coordinates: [format(coord.lng), format(coord.lat)] } end @@ -163,13 +163,13 @@ def polygon_geometry(rect) east = edge(format(rect.coord2.lng), from: -180.0, to: 180.0) south, north = [format(rect.coord1.lat), format(rect.coord2.lat)].minmax - return { type: 'Polygon', coordinates: [ring(west, east, south, north)] } unless west > east + return {type: "Polygon", coordinates: [ring(west, east, south, north)]} unless west > east # A box reads west to east, so a west edge greater than its east edge means # the box crosses the antimeridian. GeoJSON has no wrapping boxes, so such a # box is split there into two polygons (RFC 7946, section 3.1.9). { - type: 'MultiPolygon', + type: "MultiPolygon", coordinates: [ [ring(west, 180.0, south, north)], [ring(-180.0, east, south, north)] @@ -180,7 +180,7 @@ def polygon_geometry(rect) # If a box edge sits right on the antimeridian it could be counted as # 180 or -180; we pick whichever one won't require splitting (see above). def edge(lng, from:, to:) - lng == from ? to : lng + (lng == from) ? to : lng end # Exterior rings run counterclockwise (RFC 7946, section 3.1.6). diff --git a/lib/iiif/v3/presentation/range.rb b/lib/iiif/v3/presentation/range.rb index f7c13a9..25836c4 100644 --- a/lib/iiif/v3/presentation/range.rb +++ b/lib/iiif/v3/presentation/range.rb @@ -3,33 +3,33 @@ module V3 module Presentation # Ranges are linked or embedded within the manifest in a structures field class Range < Sequence - TYPE = 'Range'.freeze + TYPE = "Range".freeze VALID_ITEM_TYPES = [IIIF::V3::Presentation::Canvas, IIIF::V3::Presentation::Range] def required_keys - super + %w{ id label } + super + %w[id label] end # TODO: contentAnnotations: links to AnnotationCollection # TODO: startCanvas: A link from a Sequence or Range to a Canvas that is contained within it def array_only_keys - super + %w{ members } + super + %w[members] end def legal_viewing_hint_values - super + %w{ top } + super + %w[top] end - def initialize(hsh={}) - hsh['type'] = TYPE unless hsh.has_key? 'type' - super(hsh) + def initialize(hsh = {}) + hsh["type"] = TYPE unless hsh.has_key? "type" + super end def validate super - validate_list(self['items']) if self['items'] - validate_list(self['canvases']) if self['canvases'] + validate_list(self["items"]) if self["items"] + validate_list(self["canvases"]) if self["canvases"] # TODO: Ranges must have URIs and they should be http(s) URIs. # TODO: contentAnnotations: links to AnnotationCollection # TODO: startCanvas: A link from a Sequence or Range to a Canvas that is contained within it @@ -40,7 +40,7 @@ def validate def validate_list(canvas_array) return if canvas_array.all? { |entry| VALID_ITEM_TYPES.include?(entry.class) } - m = "All entries in the (items or canvases) array must be one of #{VALID_ITEM_TYPES.join(', ')}" + m = "All entries in the (items or canvases) array must be one of #{VALID_ITEM_TYPES.join(", ")}" raise IIIF::V3::Presentation::IllegalValueError, m end end diff --git a/lib/iiif/v3/presentation/resource.rb b/lib/iiif/v3/presentation/resource.rb index 21d270d..e8df457 100644 --- a/lib/iiif/v3/presentation/resource.rb +++ b/lib/iiif/v3/presentation/resource.rb @@ -3,23 +3,22 @@ module V3 module Presentation # class for generic content resource class Resource < IIIF::V3::AbstractResource - def required_keys - super + %w{ id } + super + %w[id] end def prohibited_keys - super + PAGING_PROPERTIES + %w{ nav_date viewing_direction start_canvas content_annotations} + super + PAGING_PROPERTIES + %w[nav_date viewing_direction start_canvas content_annotations] end def uri_only_keys - super + %w{ id } + super + %w[id] end def validate super - unless self['id'] =~ /^https?:/ + unless /^https?:/.match?(self["id"]) err_msg = "id must be an http(s) URI for #{self.class}" raise IIIF::V3::Presentation::IllegalValueError, err_msg end diff --git a/lib/iiif/v3/presentation/sequence.rb b/lib/iiif/v3/presentation/sequence.rb index 1728540..c11d257 100644 --- a/lib/iiif/v3/presentation/sequence.rb +++ b/lib/iiif/v3/presentation/sequence.rb @@ -2,8 +2,7 @@ module IIIF module V3 module Presentation class Sequence < IIIF::V3::AbstractResource - - TYPE = 'Sequence'.freeze + TYPE = "Sequence".freeze # NOTE: relaxing requirement for items as Universal Viewer currently only accepts canvases # see https://github.com/sul-dlss/osullivan/issues/27, sul-dlss/purl/issues/167 @@ -12,22 +11,22 @@ class Sequence < IIIF::V3::AbstractResource # end def prohibited_keys - super + CONTENT_RESOURCE_PROPERTIES + PAGING_PROPERTIES + %w{ nav_date content_annotations } + super + CONTENT_RESOURCE_PROPERTIES + PAGING_PROPERTIES + %w[nav_date content_annotations] end # NOTE: allowing 'items' or 'canvases' as Universal Viewer currently only accepts canvases # see https://github.com/sul-dlss/osullivan/issues/27, sul-dlss/purl/issues/167 def array_only_keys - super + %w{ canvases } + super + %w[canvases] end def legal_viewing_hint_values - %w{ individuals paged continuous auto-advance } + %w[individuals paged continuous auto-advance] end - def initialize(hsh={}) - hsh['type'] = TYPE unless hsh.has_key? 'type' - super(hsh) + def initialize(hsh = {}) + hsh["type"] = TYPE unless hsh.has_key? "type" + super end def validate @@ -36,9 +35,9 @@ def validate # Canvas object list # NOTE: allowing 'items' or 'canvases' as Universal Viewer currently only accepts canvases # see https://github.com/sul-dlss/osullivan/issues/27, sul-dlss/purl/issues/167 - unless (self['items'] && self['items'].any?) || - (self['canvases'] && self['canvases'].any?) - m = 'The (items or canvases) list must have at least one entry.' + unless self["items"]&.any? || + self["canvases"]&.any? + m = "The (items or canvases) list must have at least one entry." raise IIIF::V3::Presentation::MissingRequiredKeyError, m end # TODO: startCanvas: A link from a Sequence or Range to a Canvas that is contained within it diff --git a/lib/iiif/v3/presentation/service.rb b/lib/iiif/v3/presentation/service.rb index a36cbfd..1c206b6 100644 --- a/lib/iiif/v3/presentation/service.rb +++ b/lib/iiif/v3/presentation/service.rb @@ -3,43 +3,42 @@ module V3 module Presentation # See http://prezi3.iiif.io/api/annex/services for more info class Service < AbstractResource - # constants included here for convenience - IIIF_IMAGE_V2_TYPE = 'ImageService2'.freeze - IIIF_IMAGE_V2_LEVEL1_PROFILE = 'http://iiif.io/api/image/2/level1.json'.freeze - IIIF_AUTHENTICATION_V1_LOGIN_PROFILE = 'http://iiif.io/api/auth/1/login'.freeze - IIIF_AUTHENTICATION_V1_TOKEN_PROFILE = 'http://iiif.io/api/auth/1/token'.freeze + IIIF_IMAGE_V2_TYPE = "ImageService2".freeze + IIIF_IMAGE_V2_LEVEL1_PROFILE = "http://iiif.io/api/image/2/level1.json".freeze + IIIF_AUTHENTICATION_V1_LOGIN_PROFILE = "http://iiif.io/api/auth/1/login".freeze + IIIF_AUTHENTICATION_V1_TOKEN_PROFILE = "http://iiif.io/api/auth/1/token".freeze # service class doesn't require type def required_keys - super.reject {|el| el == 'type' } + super.reject { |el| el == "type" } end def prohibited_keys super + CONTENT_RESOURCE_PROPERTIES + PAGING_PROPERTIES + - %w{ nav_date viewing_direction start_canvas content_annotations } + %w[nav_date viewing_direction start_canvas content_annotations] end def uri_only_keys - super + %w{ @context id @id } + super + %w[@context id @id] end def any_type_keys - super + %w{ profile } + super + %w[profile] end def validate super - if IIIF_IMAGE_V2_TYPE == self['type'] || IIIF_IMAGE_V2_TYPE == self['@type'] - unless self.has_key?('id') || self.has_key?('@id') + if self["type"] == IIIF_IMAGE_V2_TYPE || self["@type"] == IIIF_IMAGE_V2_TYPE + unless has_key?("id") || has_key?("@id") m = "id or @id values are required for IIIF::V3::Presentation::Service with type or @type #{IIIF_IMAGE_V2_TYPE}" raise IIIF::V3::Presentation::MissingRequiredKeyError, m end - if self.has_key?('id') && self.has_key?('@id') && (self['@id'] != self['id']) + if has_key?("id") && has_key?("@id") && (self["@id"] != self["id"]) m = "id and @id values must match for IIIF::V3::Presentation::Service with type or @type #{IIIF_IMAGE_V2_TYPE}" raise IIIF::V3::Presentation::IllegalValueError, m end - unless self.has_key?('profile') + unless has_key?("profile") m = "profile should be present for IIIF::V3::Presentation::Service with type or @type #{IIIF_IMAGE_V2_TYPE}" raise IIIF::V3::Presentation::MissingRequiredKeyError, m end diff --git a/spec/integration/iiif/presentation/image_resource_spec.rb b/spec/integration/iiif/presentation/image_resource_spec.rb index 51ed9e9..ee7b299 100644 --- a/spec/integration/iiif/presentation/image_resource_spec.rb +++ b/spec/integration/iiif/presentation/image_resource_spec.rb @@ -1,122 +1,118 @@ describe IIIF::Presentation::ImageResource do vcr_options = { - cassette_name: 'pul_loris_cassette', + cassette_name: "pul_loris_cassette", record: :new_episodes, serialize_with: :json } - describe 'self#create_image_api_image_resource', vcr: vcr_options do - - let(:image_server) { 'https://libimages.princeton.edu/loris' } + describe "self#create_image_api_image_resource", vcr: vcr_options do + let(:image_server) { "https://libimages.princeton.edu/loris" } let(:valid_service_id) { - id = 'pudl0001%2F4612422%2F00000001.jp2' + id = "pudl0001%2F4612422%2F00000001.jp2" "#{image_server}/#{id}" } let(:invalid_service_id) { - id = 'xxxx%2F4612422%2F00000001.jp2' + id = "xxxx%2F4612422%2F00000001.jp2" "#{image_server}/#{id}" } - it 'returns an ImageResource' do + it "returns an ImageResource" do instance = described_class.create_image_api_image_resource(service_id: valid_service_id) expect(instance.class).to be described_class end - - describe 'has expected values from our fixture' do - it 'when copy_info is false' do - opts = { service_id: valid_service_id } + describe "has expected values from our fixture" do + it "when copy_info is false" do + opts = {service_id: valid_service_id} resource = described_class.create_image_api_image_resource(opts) # expect(resource['@context']).to eq 'http://iiif.io/api/presentation/2/context.json' # @context is only added when we call to_json... - expect(resource['@id']).to eq 'https://libimages.princeton.edu/loris/pudl0001%2F4612422%2F00000001.jp2/full/!200,200/0/default.jpg' - expect(resource['@type']).to eq 'dctypes:Image' + expect(resource["@id"]).to eq "https://libimages.princeton.edu/loris/pudl0001%2F4612422%2F00000001.jp2/full/!200,200/0/default.jpg" + expect(resource["@type"]).to eq "dctypes:Image" expect(resource.format).to eq "image/jpeg" expect(resource.width).to eq 3047 expect(resource.height).to eq 7200 - expect(resource.service['@context']).to eq 'http://iiif.io/api/image/2/context.json' - expect(resource.service['@id']).to eq 'https://libimages.princeton.edu/loris/pudl0001%2F4612422%2F00000001.jp2' - expect(resource.service['profile']).to eq 'http://iiif.io/api/image/2/level2.json' + expect(resource.service["@context"]).to eq "http://iiif.io/api/image/2/context.json" + expect(resource.service["@id"]).to eq "https://libimages.princeton.edu/loris/pudl0001%2F4612422%2F00000001.jp2" + expect(resource.service["profile"]).to eq "http://iiif.io/api/image/2/level2.json" end - it 'copies over all the info (when copy_info is true)' do - opts = { service_id: valid_service_id, copy_info: true } + it "copies over all the info (when copy_info is true)" do + opts = {service_id: valid_service_id, copy_info: true} resource = described_class.create_image_api_image_resource(opts) - expect(resource['@id']).to eq 'https://libimages.princeton.edu/loris/pudl0001%2F4612422%2F00000001.jp2/full/!200,200/0/default.jpg' - expect(resource['@type']).to eq 'dctypes:Image' + expect(resource["@id"]).to eq "https://libimages.princeton.edu/loris/pudl0001%2F4612422%2F00000001.jp2/full/!200,200/0/default.jpg" + expect(resource["@type"]).to eq "dctypes:Image" expect(resource.format).to eq "image/jpeg" expect(resource.width).to eq 3047 expect(resource.height).to eq 7200 - expect(resource.service['@context']).to eq 'http://iiif.io/api/image/2/context.json' - expect(resource.service['@id']).to eq 'https://libimages.princeton.edu/loris/pudl0001%2F4612422%2F00000001.jp2' - expect(resource.service['profile']).to eq [ - 'http://iiif.io/api/image/2/level2.json', + expect(resource.service["@context"]).to eq "http://iiif.io/api/image/2/context.json" + expect(resource.service["@id"]).to eq "https://libimages.princeton.edu/loris/pudl0001%2F4612422%2F00000001.jp2" + expect(resource.service["profile"]).to eq [ + "http://iiif.io/api/image/2/level2.json", { - 'supports' => [ - 'canonicalLinkHeader', 'profileLinkHeader', 'mirroring', - 'rotationArbitrary', 'regionSquare', 'sizeAboveFull' + "supports" => [ + "canonicalLinkHeader", "profileLinkHeader", "mirroring", + "rotationArbitrary", "regionSquare", "sizeAboveFull" ], - 'qualities' => ['default', 'bitonal', 'gray', 'color'], - 'formats'=>['jpg', 'png', 'gif', 'webp'] + "qualities" => ["default", "bitonal", "gray", "color"], + "formats" => ["jpg", "png", "gif", "webp"] } ] - expect(resource.service['tiles']).to eq [ { - 'width' => 1024, - 'scaleFactors' => [ 1, 2, 4, 8, 16, 32 ] - } ] - expect(resource.service['sizes']).to eq [ - {'width' => 96, 'height' => 225 }, - {'width' => 191, 'height' => 450 }, - {'width' => 381, 'height' => 900 }, - {'width' => 762, 'height' => 1800 }, - {'width' => 1524, 'height' => 3600 }, - {'width' => 3047, 'height' => 7200 } + expect(resource.service["tiles"]).to eq [{ + "width" => 1024, + "scaleFactors" => [1, 2, 4, 8, 16, 32] + }] + expect(resource.service["sizes"]).to eq [ + {"width" => 96, "height" => 225}, + {"width" => 191, "height" => 450}, + {"width" => 381, "height" => 900}, + {"width" => 762, "height" => 1800}, + {"width" => 1524, "height" => 3600}, + {"width" => 3047, "height" => 7200} ] end end - describe 'respects the params we supply' do - it ':resource_id' do - r_id = 'http://example.edu/images/some.jpg' + describe "respects the params we supply" do + it ":resource_id" do + r_id = "http://example.edu/images/some.jpg" - opts = { service_id: valid_service_id, resource_id: r_id} + opts = {service_id: valid_service_id, resource_id: r_id} resource = described_class.create_image_api_image_resource(opts) - expect(resource['@id']).to eq r_id + expect(resource["@id"]).to eq r_id end - it ':width' do + it ":width" do width = 42 - opts = { service_id: valid_service_id, width: width} + opts = {service_id: valid_service_id, width: width} resource = described_class.create_image_api_image_resource(opts) expect(resource.width).to eq width end - it ':height' do + it ":height" do height = 42 - opts = { service_id: valid_service_id, height: height} + opts = {service_id: valid_service_id, height: height} resource = described_class.create_image_api_image_resource(opts) expect(resource.height).to eq height end - it ':profile (service[\'profile\'])' do - profile = 'http://iiif.io/api/image/2/level1.json' - opts = { service_id: valid_service_id, profile: profile} + it ":profile (service['profile'])" do + profile = "http://iiif.io/api/image/2/level1.json" + opts = {service_id: valid_service_id, profile: profile} resource = described_class.create_image_api_image_resource(opts) - expect(resource.service['profile']).to eq profile + expect(resource.service["profile"]).to eq profile end end - describe 'errors' do - it 'raises if :service_id is not included' do + describe "errors" do + it "raises if :service_id is not included" do expect { described_class.create_image_api_image_resource }.to raise_error end - it 'raises if the info can\'t be pulled in' do + it "raises if the info can't be pulled in" do expect { described_class.create_image_api_image_resource(service_id: invalid_service_id) }.to raise_error end end - - end end diff --git a/spec/integration/iiif/service_spec.rb b/spec/integration/iiif/service_spec.rb index 48e085a..3afb094 100644 --- a/spec/integration/iiif/service_spec.rb +++ b/spec/integration/iiif/service_spec.rb @@ -1,43 +1,43 @@ RSpec.describe IIIF::Service do + let(:fixtures_dir) { File.join(File.dirname(__FILE__), "../../fixtures") } + let(:manifest_from_spec_path) { File.join(fixtures_dir, "manifests/complete_from_spec.json") } - let(:fixtures_dir) { File.join(File.dirname(__FILE__), '../../fixtures') } - let(:manifest_from_spec_path) { File.join(fixtures_dir, 'manifests/complete_from_spec.json') } - - describe 'self.parse' do - it 'works from a file' do + describe "self.parse" do + it "works from a file" do s = described_class.parse(manifest_from_spec_path) - expect(s['label']).to eq 'Book 1' + expect(s["label"]).to eq "Book 1" end - it 'works from a string of JSON' do - file = File.open(manifest_from_spec_path, 'rb') + it "works from a string of JSON" do + file = File.open(manifest_from_spec_path, "rb") json_string = file.read file.close s = described_class.parse(json_string) - expect(s['label']).to eq 'Book 1' + expect(s["label"]).to eq "Book 1" end - describe 'works from a hash' do - it 'plain old' do + describe "works from a hash" do + it "plain old" do h = JSON.parse(IO.read(manifest_from_spec_path)) s = described_class.parse(h) - expect(s['label']).to eq 'Book 1' + expect(s["label"]).to eq "Book 1" end - it 'IIIF::OrderedHash' do + it "IIIF::OrderedHash" do h = JSON.parse(IO.read(manifest_from_spec_path)) oh = IIIF::OrderedHash[h] s = described_class.parse(oh) - expect(s['label']).to eq 'Book 1' + expect(s["label"]).to eq "Book 1" end end - it 'turns camels to snakes' do + it "turns camels to snakes" do s = described_class.parse(manifest_from_spec_path) - expect(s.keys.include?('see_also')).to be_truthy - expect(s.keys.include?('seeAlso')).to be_falsey + expect(s.key?("see_also")).to be_truthy + expect(s.key?("seeAlso")).to be_falsey end end - describe 'self#from_ordered_hash' do + describe "self#from_ordered_hash" do subject(:parsed) { described_class.from_ordered_hash(fixture) } - let(:fixture) { JSON.parse('{ + let(:fixture) { + JSON.parse('{ "@context": "http://iiif.io/api/presentation/2/context.json", "@id": "http://example.com/manifest", "@type": "sc:Manifest", @@ -84,33 +84,31 @@ ] }') } - it 'doesn\'t raise a NoMethodError when we check the keys' do + it "doesn't raise a NoMethodError when we check the keys" do expect { parsed }.to_not raise_error end - it 'turns the fixture into a Manifest instance' do + it "turns the fixture into a Manifest instance" do expect(parsed).to be_a IIIF::Presentation::Manifest end it 'turns keys without "@type" into an OrderedHash' do - expect(parsed['some_other_thing']).to be_a IIIF::OrderedHash + expect(parsed["some_other_thing"]).to be_a IIIF::OrderedHash end - it 'turns services into Services' do - expect(parsed['service']).to be_a IIIF::Presentation::Service + it "turns services into Services" do + expect(parsed["service"]).to be_a IIIF::Presentation::Service end - it 'works with arrays of services' do - fixture['service'] = [fixture['service']] - expect(parsed['service'].first).to be_a IIIF::Presentation::Service + it "works with arrays of services" do + fixture["service"] = [fixture["service"]] + expect(parsed["service"].first).to be_a IIIF::Presentation::Service end - it 'round-trips' do - fp = '/tmp/osullivan-spec.json' - File.open(fp,'w') do |f| - f.write(parsed.to_json) - end - from_file = IIIF::Service.parse('/tmp/osullivan-spec.json') + it "round-trips" do + fp = "/tmp/osullivan-spec.json" + File.write(fp, parsed.to_json) + from_file = IIIF::Service.parse("/tmp/osullivan-spec.json") File.delete(fp) # is this sufficient? expect(parsed.to_ordered_hash.to_a - from_file.to_ordered_hash.to_a).to eq [] @@ -118,86 +116,87 @@ end it 'turns each memeber of "sequences" into an instance of Sequence' do - expect(parsed['sequences']).to all be_a IIIF::Presentation::Sequence + expect(parsed["sequences"]).to all be_a IIIF::Presentation::Sequence end - it 'turns each member of sequences/canvaes in an instance of Canvas' do - parsed['sequences'].each do |s| + it "turns each member of sequences/canvaes in an instance of Canvas" do + parsed["sequences"].each do |s| expect(s.canvases).to all be_a IIIF::Presentation::Canvas end end - it 'turns the keys into snakes' do - expect(parsed.has_key?('seeAlso')).to be false - expect(parsed.has_key?('see_also')).to be true + it "turns the keys into snakes" do + expect(parsed.has_key?("seeAlso")).to be false + expect(parsed.has_key?("see_also")).to be true end - it 'copies over plain-old key-values' do - expect(parsed['label']).to eq 'My Manifest' + it "copies over plain-old key-values" do + expect(parsed["label"]).to eq "My Manifest" end end - describe '#to_ordered_hash' do - let(:logo_uri) { 'http://www.example.org/logos/institution1.jpg' } - let(:within_uri) { 'http://www.example.org/collections/books/' } - let(:see_also) { 'http://www.example.org/library/catalog/book1.xml' } - - describe 'it puts the json-ld keys at the top' do - let(:extra_props) { [ - ['label','foo'], - ['logo','http://example.com/logo.jpg'], - ['within','http://example.com/something'] - ] } - let(:sorted_ld_keys) { - subject.keys.select { |k| k.start_with?('@') }.sort! + describe "#to_ordered_hash" do + let(:logo_uri) { "http://www.example.org/logos/institution1.jpg" } + let(:within_uri) { "http://www.example.org/collections/books/" } + let(:see_also) { "http://www.example.org/library/catalog/book1.xml" } + + describe "it puts the json-ld keys at the top" do + let(:extra_props) { + [ + ["label", "foo"], + ["logo", "http://example.com/logo.jpg"], + ["within", "http://example.com/something"] + ] } - before(:each) { - extra_props.reverse.each do |k,v| - subject.unshift(k,v) + let(:sorted_ld_keys) { + subject.keys.select { |k| k.start_with?("@") }.sort! + } + before(:each) { + extra_props.reverse_each do |k, v| + subject.unshift(k, v) end } - it 'by default' do - (0..extra_props.length-1).each do |i| + it "by default" do + (0..extra_props.length - 1).each do |i| expect(subject.keys[i]).to eq(extra_props[i][0]) end oh = subject.to_ordered_hash - (0..sorted_ld_keys.length-1).each do |i| + (0..sorted_ld_keys.length - 1).each do |i| expect(oh.keys[i]).to eq(sorted_ld_keys[i]) end end - it 'unless you say not to' do - (0..extra_props.length-1).each do |i| + it "unless you say not to" do + (0..extra_props.length - 1).each do |i| expect(subject.keys[i]).to eq(extra_props[i][0]) end oh = subject.to_ordered_hash(sort_json_ld_keys: false) - (0..extra_props.length-1).each do |i| + (0..extra_props.length - 1).each do |i| expect(oh.keys[i]).to eq(extra_props[i][0]) end end end - describe 'removes empty keys' do - it 'if they\'re arrays' do - subject['logo'] = logo_uri - subject['within'] = [] + describe "removes empty keys" do + it "if they're arrays" do + subject["logo"] = logo_uri + subject["within"] = [] ordered_hash = subject.to_ordered_hash - expect(ordered_hash.has_key?('within')).to be_falsey + expect(ordered_hash.has_key?("within")).to be_falsey end - it 'if they\'re nil' do - subject['logo'] = logo_uri - subject['within'] = nil + it "if they're nil" do + subject["logo"] = logo_uri + subject["within"] = nil ordered_hash = subject.to_ordered_hash - expect(ordered_hash.has_key?('within')).to be_falsey + expect(ordered_hash.has_key?("within")).to be_falsey end end - it 'converts snake_case keys to camelCase' do - subject['see_also'] = logo_uri - subject['within'] = within_uri + it "converts snake_case keys to camelCase" do + subject["see_also"] = logo_uri + subject["within"] = within_uri ordered_hash = subject.to_ordered_hash - expect(ordered_hash.keys.include?('seeAlso')).to be_truthy + expect(ordered_hash.key?("seeAlso")).to be_truthy end end - end diff --git a/spec/integration/iiif/v3/abstract_resource_spec.rb b/spec/integration/iiif/v3/abstract_resource_spec.rb index 88b0fe0..940db0f 100644 --- a/spec/integration/iiif/v3/abstract_resource_spec.rb +++ b/spec/integration/iiif/v3/abstract_resource_spec.rb @@ -1,45 +1,45 @@ -require 'active_support/inflector' -require 'json' +require "active_support/inflector" +require "json" describe IIIF::V3::AbstractResource do + let(:fixtures_dir) { File.join(File.dirname(__FILE__), "../../../fixtures") } + let(:manifest_from_spec_path) { File.join(fixtures_dir, "v3/manifests/complete_from_spec.json") } - let(:fixtures_dir) { File.join(File.dirname(__FILE__), '../../../fixtures') } - let(:manifest_from_spec_path) { File.join(fixtures_dir, 'v3/manifests/complete_from_spec.json') } - - describe 'self.parse' do - it 'works from a file' do + describe "self.parse" do + it "works from a file" do s = described_class.parse(manifest_from_spec_path) - expect(s['label']['en']).to include 'Book 1' + expect(s["label"]["en"]).to include "Book 1" end - it 'works from a string of JSON' do - file = File.open(manifest_from_spec_path, 'rb') + it "works from a string of JSON" do + file = File.open(manifest_from_spec_path, "rb") json_string = file.read file.close s = described_class.parse(json_string) - expect(s['label']['en']).to include 'Book 1' + expect(s["label"]["en"]).to include "Book 1" end - describe 'works from a hash' do - it 'plain old' do + describe "works from a hash" do + it "plain old" do h = JSON.parse(IO.read(manifest_from_spec_path)) s = described_class.parse(h) - expect(s['label']['en']).to include 'Book 1' + expect(s["label"]["en"]).to include "Book 1" end - it 'IIIF::OrderedHash' do + it "IIIF::OrderedHash" do h = JSON.parse(IO.read(manifest_from_spec_path)) oh = IIIF::OrderedHash[h] s = described_class.parse(oh) - expect(s['label']['en']).to include 'Book 1' + expect(s["label"]["en"]).to include "Book 1" end end - it 'turns camels to snakes' do + it "turns camels to snakes" do s = described_class.parse(manifest_from_spec_path) - expect(s.keys.include?('see_also')).to be_truthy - expect(s.keys.include?('seeAlso')).to be_falsey + expect(s.key?("see_also")).to be_truthy + expect(s.key?("seeAlso")).to be_falsey end end - describe 'self#from_ordered_hash' do - let(:fixture) { JSON.parse('{ + describe "self#from_ordered_hash" do + let(:fixture) { + JSON.parse('{ "@context": [ "http://iiif.io/api/presentation/3/context.json", "http://www.w3.org/ns/anno.jsonld" @@ -81,10 +81,10 @@ ] }') } - it 'doesn\'t raise a NoMethodError when we check the keys' do + it "doesn't raise a NoMethodError when we check the keys" do expect { described_class.from_ordered_hash(fixture) }.to_not raise_error end - it 'turns the fixture into a Manifest instance' do + it "turns the fixture into a Manifest instance" do expected_klass = IIIF::V3::Presentation::Manifest parsed = described_class.from_ordered_hash(fixture) expect(parsed.class).to be expected_klass @@ -92,22 +92,20 @@ it 'turns keys without "type" into an OrderedHash' do expected_klass = IIIF::OrderedHash parsed = described_class.from_ordered_hash(fixture) - expect(parsed['some_other_thing'].class).to be expected_klass + expect(parsed["some_other_thing"].class).to be expected_klass end - it 'turns services into Services' do + it "turns services into Services" do expected_klass = IIIF::V3::Presentation::Service parsed = described_class.from_ordered_hash(fixture) - expect(parsed['service'].map(&:class).uniq).to contain_exactly expected_klass + expect(parsed["service"].map(&:class).uniq).to contain_exactly expected_klass end - it 'round-trips' do - fp = '/tmp/osullivan-spec.json' + it "round-trips" do + fp = "/tmp/osullivan-spec.json" parsed = described_class.from_ordered_hash(fixture) - File.open(fp,'w') do |f| - f.write(parsed.to_json) - end - from_file = IIIF::V3::Presentation::Service.parse('/tmp/osullivan-spec.json') + File.write(fp, parsed.to_json) + from_file = IIIF::V3::Presentation::Service.parse("/tmp/osullivan-spec.json") File.delete(fp) # is this sufficient? expect(parsed.to_ordered_hash.to_a - from_file.to_ordered_hash.to_a).to eq [] @@ -115,91 +113,92 @@ end it 'turns each member of "items" into an instance of Sequence' do parsed = described_class.from_ordered_hash(fixture) - parsed['items'].each do |s| + parsed["items"].each do |s| expect(s.class).to be IIIF::V3::Presentation::Canvas end end - it 'turns each member of sequences/items into an instance of Canvas' do + it "turns each member of sequences/items into an instance of Canvas" do parsed = described_class.from_ordered_hash(fixture) - parsed['items'].each do |s| + parsed["items"].each do |s| s.items.each do |c| expect(c.class).to be IIIF::V3::Presentation::Canvas end end end - it 'turns the keys into snakes' do - expect(described_class.from_ordered_hash(fixture).has_key?('seeAlso')).to be_falsey - expect(described_class.from_ordered_hash(fixture).has_key?('see_also')).to be_truthy + it "turns the keys into snakes" do + expect(described_class.from_ordered_hash(fixture).has_key?("seeAlso")).to be_falsey + expect(described_class.from_ordered_hash(fixture).has_key?("see_also")).to be_truthy end - it 'copies over plain-old key-values' do + it "copies over plain-old key-values" do parsed = described_class.from_ordered_hash(fixture) - expect(parsed['label']).to eq 'My Manifest' + expect(parsed["label"]).to eq "My Manifest" end end - describe '#to_ordered_hash' do - let(:logo_uri) { 'http://www.example.org/logos/institution1.jpg' } - let(:within_uri) { 'http://www.example.org/collections/books/' } - let(:see_also) { 'http://www.example.org/library/catalog/book1.xml' } + describe "#to_ordered_hash" do + let(:logo_uri) { "http://www.example.org/logos/institution1.jpg" } + let(:within_uri) { "http://www.example.org/collections/books/" } + let(:see_also) { "http://www.example.org/library/catalog/book1.xml" } # NOTE: Using Service to test, as we can't initialize the abstract class let(:instantiated_class) { IIIF::V3::Presentation::Service.new } - describe 'it puts the json-ld keys at the top' do - let(:extra_props) { [ - ['label','foo'], - ['logo','http://example.com/logo.jpg'], - ['within','http://example.com/something'] - ] } + describe "it puts the json-ld keys at the top" do + let(:extra_props) { + [ + ["label", "foo"], + ["logo", "http://example.com/logo.jpg"], + ["within", "http://example.com/something"] + ] + } let(:sorted_ld_keys) { - instantiated_class.keys.select { |k| k.start_with?('@') }.sort! + instantiated_class.keys.select { |k| k.start_with?("@") }.sort! } before(:each) { - extra_props.reverse.each do |k,v| - instantiated_class.unshift(k,v) + extra_props.reverse_each do |k, v| + instantiated_class.unshift(k, v) end } - it 'by default' do - (0..extra_props.length-1).each do |i| + it "by default" do + (0..extra_props.length - 1).each do |i| expect(instantiated_class.keys[i]).to eq(extra_props[i][0]) end oh = instantiated_class.to_ordered_hash - (0..sorted_ld_keys.length-1).each do |i| + (0..sorted_ld_keys.length - 1).each do |i| expect(oh.keys[i]).to eq(sorted_ld_keys[i]) end end - it 'unless you say not to' do - (0..extra_props.length-1).each do |i| + it "unless you say not to" do + (0..extra_props.length - 1).each do |i| expect(instantiated_class.keys[i]).to eq(extra_props[i][0]) end oh = instantiated_class.to_ordered_hash(sort_json_ld_keys: false) - (0..extra_props.length-1).each do |i| + (0..extra_props.length - 1).each do |i| expect(oh.keys[i]).to eq(extra_props[i][0]) end end end - describe 'removes empty keys' do - it 'if they\'re arrays' do - instantiated_class['logo'] = logo_uri - instantiated_class['within'] = [] + describe "removes empty keys" do + it "if they're arrays" do + instantiated_class["logo"] = logo_uri + instantiated_class["within"] = [] ordered_hash = instantiated_class.to_ordered_hash - expect(ordered_hash.has_key?('within')).to be_falsey + expect(ordered_hash.has_key?("within")).to be_falsey end - it 'if they\'re nil' do - instantiated_class['logo'] = logo_uri - instantiated_class['within'] = nil + it "if they're nil" do + instantiated_class["logo"] = logo_uri + instantiated_class["within"] = nil ordered_hash = instantiated_class.to_ordered_hash - expect(ordered_hash.has_key?('within')).to be_falsey + expect(ordered_hash.has_key?("within")).to be_falsey end end - it 'converts snake_case keys to camelCase' do - instantiated_class['see_also'] = logo_uri - instantiated_class['within'] = within_uri + it "converts snake_case keys to camelCase" do + instantiated_class["see_also"] = logo_uri + instantiated_class["within"] = within_uri ordered_hash = instantiated_class.to_ordered_hash - expect(ordered_hash.keys.include?('seeAlso')).to be_truthy + expect(ordered_hash.key?("seeAlso")).to be_truthy end end - end diff --git a/spec/integration/iiif/v3/presentation/image_resource_spec.rb b/spec/integration/iiif/v3/presentation/image_resource_spec.rb index 89751c5..d9c3958 100644 --- a/spec/integration/iiif/v3/presentation/image_resource_spec.rb +++ b/spec/integration/iiif/v3/presentation/image_resource_spec.rb @@ -1,118 +1,115 @@ describe IIIF::V3::Presentation::ImageResource do vcr_options = { - cassette_name: 'pul_loris_cassette_v3', + cassette_name: "pul_loris_cassette_v3", record: :new_episodes, serialize_with: :json } - describe 'self#create_image_api_image_resource', vcr: vcr_options do - - let(:image_server) { 'https://libimages.princeton.edu/loris' } + describe "self#create_image_api_image_resource", vcr: vcr_options do + let(:image_server) { "https://libimages.princeton.edu/loris" } let(:valid_service_id) { - id = 'pudl0001%2F4612422%2F00000001.jp2' + id = "pudl0001%2F4612422%2F00000001.jp2" "#{image_server}/#{id}" } let(:invalid_service_id) { - id = 'xxxx%2F4612422%2F00000001.jp2' + id = "xxxx%2F4612422%2F00000001.jp2" "#{image_server}/#{id}" } - it 'returns an ImageResource' do + it "returns an ImageResource" do instance = described_class.create_image_api_image_resource(service_id: valid_service_id) expect(instance.class).to be described_class end - - describe 'has expected values from our fixture' do - it 'when copy_info is false' do - opts = { service_id: valid_service_id } + describe "has expected values from our fixture" do + it "when copy_info is false" do + opts = {service_id: valid_service_id} resource = described_class.create_image_api_image_resource(opts) - expect(resource['id']).to eq 'https://libimages.princeton.edu/loris/pudl0001%2F4612422%2F00000001.jp2/full/!200,200/0/default.jpg' - expect(resource['type']).to eq 'Image' + expect(resource["id"]).to eq "https://libimages.princeton.edu/loris/pudl0001%2F4612422%2F00000001.jp2/full/!200,200/0/default.jpg" + expect(resource["type"]).to eq "Image" expect(resource.format).to eq "image/jpeg" expect(resource.width).to eq 3047 expect(resource.height).to eq 7200 - expect(resource.service.first['id']).to eq 'https://libimages.princeton.edu/loris/pudl0001%2F4612422%2F00000001.jp2' - expect(resource.service.first['profile']).to eq 'http://iiif.io/api/image/2/level2.json' + expect(resource.service.first["id"]).to eq "https://libimages.princeton.edu/loris/pudl0001%2F4612422%2F00000001.jp2" + expect(resource.service.first["profile"]).to eq "http://iiif.io/api/image/2/level2.json" end - it 'copies over all teh infos (when copy_info is true)' do - opts = { service_id: valid_service_id, copy_info: true } + it "copies over all teh infos (when copy_info is true)" do + opts = {service_id: valid_service_id, copy_info: true} resource = described_class.create_image_api_image_resource(opts) - expect(resource['id']).to eq 'https://libimages.princeton.edu/loris/pudl0001%2F4612422%2F00000001.jp2/full/!200,200/0/default.jpg' - expect(resource['type']).to eq 'Image' + expect(resource["id"]).to eq "https://libimages.princeton.edu/loris/pudl0001%2F4612422%2F00000001.jp2/full/!200,200/0/default.jpg" + expect(resource["type"]).to eq "Image" expect(resource.format).to eq "image/jpeg" expect(resource.width).to eq 3047 expect(resource.height).to eq 7200 - expect(resource.service.first['profile']).to eq [ - 'http://iiif.io/api/image/2/level2.json', + expect(resource.service.first["profile"]).to eq [ + "http://iiif.io/api/image/2/level2.json", { - 'supports' => [ - 'canonicalLinkHeader', 'profileLinkHeader', 'mirroring', - 'rotationArbitrary', 'regionSquare', 'sizeAboveFull' + "supports" => [ + "canonicalLinkHeader", "profileLinkHeader", "mirroring", + "rotationArbitrary", "regionSquare", "sizeAboveFull" ], - 'qualities' => ['default', 'bitonal', 'gray', 'color'], - 'formats'=>['jpg', 'png', 'gif', 'webp'] + "qualities" => ["default", "bitonal", "gray", "color"], + "formats" => ["jpg", "png", "gif", "webp"] } ] - expect(resource.service.first['tiles']).to eq [ { - 'width' => 1024, - 'scaleFactors' => [ 1, 2, 4, 8, 16, 32 ] - } ] - expect(resource.service.first['sizes']).to eq [ - {'width' => 96, 'height' => 225 }, - {'width' => 191, 'height' => 450 }, - {'width' => 381, 'height' => 900 }, - {'width' => 762, 'height' => 1800 }, - {'width' => 1524, 'height' => 3600 }, - {'width' => 3047, 'height' => 7200 } + expect(resource.service.first["tiles"]).to eq [{ + "width" => 1024, + "scaleFactors" => [1, 2, 4, 8, 16, 32] + }] + expect(resource.service.first["sizes"]).to eq [ + {"width" => 96, "height" => 225}, + {"width" => 191, "height" => 450}, + {"width" => 381, "height" => 900}, + {"width" => 762, "height" => 1800}, + {"width" => 1524, "height" => 3600}, + {"width" => 3047, "height" => 7200} ] - expect(resource.service.first['id']).to eq 'https://libimages.princeton.edu/loris/pudl0001%2F4612422%2F00000001.jp2' - expect(resource.service.first).not_to have_key('@id') + expect(resource.service.first["id"]).to eq "https://libimages.princeton.edu/loris/pudl0001%2F4612422%2F00000001.jp2" + expect(resource.service.first).not_to have_key("@id") end end - describe 'respects the params we supply' do - it ':resource_id' do - r_id = 'http://example.edu/images/some.jpg' - opts = { service_id: valid_service_id, resource_id: r_id} + describe "respects the params we supply" do + it ":resource_id" do + r_id = "http://example.edu/images/some.jpg" + opts = {service_id: valid_service_id, resource_id: r_id} resource = described_class.create_image_api_image_resource(opts) - expect(resource['id']).to eq r_id + expect(resource["id"]).to eq r_id end - it ':width' do + it ":width" do width = 42 - opts = { service_id: valid_service_id, width: width} + opts = {service_id: valid_service_id, width: width} resource = described_class.create_image_api_image_resource(opts) expect(resource.width).to eq width end - it ':height' do + it ":height" do height = 42 - opts = { service_id: valid_service_id, height: height} + opts = {service_id: valid_service_id, height: height} resource = described_class.create_image_api_image_resource(opts) expect(resource.height).to eq height end - it ':profile (service[\'profile\'])' do - profile = 'http://iiif.io/api/image/2/level1.json' - opts = { service_id: valid_service_id, profile: profile} + it ":profile (service['profile'])" do + profile = "http://iiif.io/api/image/2/level1.json" + opts = {service_id: valid_service_id, profile: profile} resource = described_class.create_image_api_image_resource(opts) - expect(resource.service.first['profile']).to eq profile + expect(resource.service.first["profile"]).to eq profile end end - describe 'errors' do - it 'raises if :service_id is not included' do + describe "errors" do + it "raises if :service_id is not included" do expect { described_class.create_image_api_image_resource }.to raise_error end - it 'raises if the info can\'t be pulled in' do + it "raises if the info can't be pulled in" do expect { described_class.create_image_api_image_resource(service_id: invalid_service_id) }.to raise_error end end - end end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index 00ef2e5..89b6501 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,19 +1,19 @@ -require 'iiif/presentation' -require 'iiif/v3/presentation' -require 'simplecov' -require 'coveralls' -require 'debug' +require "iiif/presentation" +require "iiif/v3/presentation" +require "simplecov" +require "coveralls" +require "debug" Dir["#{File.dirname(__FILE__)}/unit/iiif/presentation/shared_examples/*.rb"].each do |f| require f end Dir["#{File.dirname(__FILE__)}/unit/iiif/v3/presentation/shared_examples/*.rb"].each do |f| require f end -require 'vcr' -require 'webmock/rspec' +require "vcr" +require "webmock/rspec" VCR.configure do |c| - c.cassette_library_dir = 'spec/fixtures/vcr_cassettes' + c.cassette_library_dir = "spec/fixtures/vcr_cassettes" c.hook_into :faraday c.configure_rspec_metadata! end @@ -23,7 +23,7 @@ Coveralls::SimpleCov::Formatter ] SimpleCov.start do - add_filter 'spec/' + add_filter "spec/" end # This file was generated by the `rspec --init` command. Conventionally, all @@ -66,52 +66,50 @@ mocks.verify_partial_doubles = true end -# The settings below are suggested to provide a good initial experience -# with RSpec, but feel free to customize to your heart's content. -=begin - # These two settings work together to allow you to limit a spec run - # to individual examples or groups you care about by tagging them with - # `:focus` metadata. When nothing is tagged with `:focus`, all examples - # get run. - config.filter_run :focus - config.run_all_when_everything_filtered = true - - # Limits the available syntax to the non-monkey patched syntax that is recommended. - # For more details, see: - # - http://myronmars.to/n/dev-blog/2012/06/rspecs-new-expectation-syntax - # - http://teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/ - # - http://myronmars.to/n/dev-blog/2014/05/notable-changes-in-rspec-3#new__config_option_to_disable_rspeccore_monkey_patching - config.disable_monkey_patching! - - # This setting enables warnings. It's recommended, but in some cases may - # be too noisy due to issues in dependencies. - config.warnings = true - - # Many RSpec users commonly either run the entire suite or an individual - # file, and it's useful to allow more verbose output when running an - # individual spec file. - if config.files_to_run.one? - # Use the documentation formatter for detailed output, - # unless a formatter has already been configured - # (e.g. via a command-line flag). - config.default_formatter = 'doc' - end - - # Print the 10 slowest examples and example groups at the - # end of the spec run, to help surface which specs are running - # particularly slow. - config.profile_examples = 10 - - # Run specs in random order to surface order dependencies. If you find an - # order dependency and want to debug it, you can fix the order by providing - # the seed, which is printed after each run. - # --seed 1234 - config.order = :random - - # Seed global randomization in this process using the `--seed` CLI option. - # Setting this allows you to use `--seed` to deterministically reproduce - # test failures related to randomization by passing the same `--seed` value - # as the one that triggered the failure. - Kernel.srand config.seed -=end + # The settings below are suggested to provide a good initial experience + # with RSpec, but feel free to customize to your heart's content. + # # These two settings work together to allow you to limit a spec run + # # to individual examples or groups you care about by tagging them with + # # `:focus` metadata. When nothing is tagged with `:focus`, all examples + # # get run. + # config.filter_run :focus + # config.run_all_when_everything_filtered = true + # + # # Limits the available syntax to the non-monkey patched syntax that is recommended. + # # For more details, see: + # # - http://myronmars.to/n/dev-blog/2012/06/rspecs-new-expectation-syntax + # # - http://teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/ + # # - http://myronmars.to/n/dev-blog/2014/05/notable-changes-in-rspec-3#new__config_option_to_disable_rspeccore_monkey_patching + # config.disable_monkey_patching! + # + # # This setting enables warnings. It's recommended, but in some cases may + # # be too noisy due to issues in dependencies. + # config.warnings = true + # + # # Many RSpec users commonly either run the entire suite or an individual + # # file, and it's useful to allow more verbose output when running an + # # individual spec file. + # if config.files_to_run.one? + # # Use the documentation formatter for detailed output, + # # unless a formatter has already been configured + # # (e.g. via a command-line flag). + # config.default_formatter = 'doc' + # end + # + # # Print the 10 slowest examples and example groups at the + # # end of the spec run, to help surface which specs are running + # # particularly slow. + # config.profile_examples = 10 + # + # # Run specs in random order to surface order dependencies. If you find an + # # order dependency and want to debug it, you can fix the order by providing + # # the seed, which is printed after each run. + # # --seed 1234 + # config.order = :random + # + # # Seed global randomization in this process using the `--seed` CLI option. + # # Setting this allows you to use `--seed` to deterministically reproduce + # # test failures related to randomization by passing the same `--seed` value + # # as the one that triggered the failure. + # Kernel.srand config.seed end diff --git a/spec/unit/iiif/hash_behaviours_spec.rb b/spec/unit/iiif/hash_behaviours_spec.rb index ac8b5e4..2ee535b 100644 --- a/spec/unit/iiif/hash_behaviours_spec.rb +++ b/spec/unit/iiif/hash_behaviours_spec.rb @@ -1,12 +1,12 @@ -require File.join(File.dirname(__FILE__), '../../spec_helper') -require 'active_support/ordered_hash' +require File.join(File.dirname(__FILE__), "../../spec_helper") +require "active_support/ordered_hash" describe IIIF::HashBehaviours do - let(:hash_like_class) do Class.new do include IIIF::HashBehaviours + attr_accessor :data # Accessible for easier expects...not sure you'd do this in a real class - def initialize() + def initialize @data = IIIF::OrderedHash.new end end @@ -15,291 +15,290 @@ def initialize() # TODO: let(:init_data)...rather than repeating so much below subject { hash_like_class.new } - describe '#[]=' do - it 'assigns a new k and value to the node' do - subject['foo'] = 'bar' - expect(subject.data).to eq({'foo' => 'bar'}) - end - it 'always puts new entries at the end' do - subject['baz'] = 'qux' - subject['quux'] = 'corge' - subject['grault'] = 'garply' - expect(subject.data[subject.data.keys.last]).to eq 'garply' - end - it 'replaces keys that already exist in the same place' do - subject['waldo'] = 'fred' - subject['plugh'] = 'xyzzy' - subject['thud'] = 'wibble' - subject['plugh'] = 'wobble' - expect(subject.data.select {|k,v| k == 'plugh'}).to eq({'plugh'=>'wobble'}) + describe "#[]=" do + it "assigns a new k and value to the node" do + subject["foo"] = "bar" + expect(subject.data).to eq({"foo" => "bar"}) + end + it "always puts new entries at the end" do + subject["baz"] = "qux" + subject["quux"] = "corge" + subject["grault"] = "garply" + expect(subject.data[subject.data.keys.last]).to eq "garply" + end + it "replaces keys that already exist in the same place" do + subject["waldo"] = "fred" + subject["plugh"] = "xyzzy" + subject["thud"] = "wibble" + subject["plugh"] = "wobble" + expect(subject.data.slice("plugh")).to eq({"plugh" => "wobble"}) end end - describe '#[]' do - it 'retrieves the expected value' do - subject['wibble'] = 'wobble' - subject['wubble'] = 'fred' - expect(subject['wibble']).to eq 'wobble' + describe "#[]" do + it "retrieves the expected value" do + subject["wibble"] = "wobble" + subject["wubble"] = "fred" + expect(subject["wibble"]).to eq "wobble" end - it 'returns nil if the key is not found' do - subject['wibble'] = 'wobble' - subject['wubble'] = 'fred' - expect(subject['flob']).to be_nil + it "returns nil if the key is not found" do + subject["wibble"] = "wobble" + subject["wubble"] = "fred" + expect(subject["flob"]).to be_nil end end - describe '#clear' do - it 'clears all properties' do - subject['wibble'] = 'wobble' - subject['wubble'] = 'fred' + describe "#clear" do + it "clears all properties" do + subject["wibble"] = "wobble" + subject["wubble"] = "fred" subject.clear expect(subject.keys).to eq [] end - it 'returns the instance on which it was called' do - subject['wibble'] = 'wobble' - subject['wubble'] = 'fred' + it "returns the instance on which it was called" do + subject["wibble"] = "wobble" + subject["wubble"] = "fred" expect(subject.clear).to eq subject end end - describe '#delete' do - it 'removes an entry from the object' do - subject['waldo'] = 'fred' - subject['plugh'] = 'xyzzy' - subject.delete('waldo') - expect(subject.data).to eq({'plugh' => 'xyzzy'}) - end - it 'returns the value of the entry that was removed' do - subject['waldo'] = 'fred' - subject['plugh'] = 'xyzzy' - expect(subject.delete('waldo')).to eq 'fred' - end - it 'can take a block as well' do - subject['waldo'] = 'fred' - subject['plugh'] = 'xyzzy' - expect { |b| subject.delete('wubble', &b) }.to yield_with_args - expect(subject.delete('foo') {|e| e.reverse }).to eq 'oof' + describe "#delete" do + it "removes an entry from the object" do + subject["waldo"] = "fred" + subject["plugh"] = "xyzzy" + subject.delete("waldo") + expect(subject.data).to eq({"plugh" => "xyzzy"}) + end + it "returns the value of the entry that was removed" do + subject["waldo"] = "fred" + subject["plugh"] = "xyzzy" + expect(subject.delete("waldo")).to eq "fred" + end + it "can take a block as well" do + subject["waldo"] = "fred" + subject["plugh"] = "xyzzy" + expect { |b| subject.delete("wubble", &b) }.to yield_with_args + expect(subject.delete("foo") { |e| e.reverse }).to eq "oof" end end - describe '#delete_if' do - it 'can take a block' do - subject['wibble'] = 'foo' - subject['waldo'] = 'fred' - subject['plugh'] = 'xyzzy' - expect { |b| subject.delete_if(&b) }.to yield_successive_args(['wibble', 'foo'], ['waldo', 'fred'], ['plugh', 'xyzzy']) - end - it 'returns the instance' do - subject['wibble'] = 'foo' - subject['waldo'] = 'fred' - subject['plugh'] = 'xyzzy' - expect( subject.delete_if { |k,v| k.start_with?('w') } ).to eq subject - end - it 'works' do - subject['wibble'] = 'foo' - subject['waldo'] = 'fred' - subject['plugh'] = 'xyzzy' - subject.delete_if { |k,v| k.start_with?('w') } - expect(subject.data).to eq({'plugh' => 'xyzzy'}) - end - it 'returns an enumerator if no block is supplied' do - subject['wibble'] = 'foo' - subject['waldo'] = 'fred' - subject['plugh'] = 'xyzzy' + describe "#delete_if" do + it "can take a block" do + subject["wibble"] = "foo" + subject["waldo"] = "fred" + subject["plugh"] = "xyzzy" + expect { |b| subject.delete_if(&b) }.to yield_successive_args(["wibble", "foo"], ["waldo", "fred"], ["plugh", "xyzzy"]) + end + it "returns the instance" do + subject["wibble"] = "foo" + subject["waldo"] = "fred" + subject["plugh"] = "xyzzy" + expect(subject.delete_if { |k, v| k.start_with?("w") }).to eq subject + end + it "works" do + subject["wibble"] = "foo" + subject["waldo"] = "fred" + subject["plugh"] = "xyzzy" + subject.delete_if { |k, v| k.start_with?("w") } + expect(subject.data).to eq({"plugh" => "xyzzy"}) + end + it "returns an enumerator if no block is supplied" do + subject["wibble"] = "foo" + subject["waldo"] = "fred" + subject["plugh"] = "xyzzy" expect(subject.delete_if).to be_a Enumerator end end - describe '#each' do - it 'yields' do - subject['plugh'] = 'xyzzy' + describe "#each" do + it "yields" do + subject["plugh"] = "xyzzy" expect { |b| subject.each(&b) }.to yield_with_args end - it 'returns the instance' do - subject.data['waldo'] = 'fred' - subject.data['plugh'] = 'xyzzy' - expect(subject.each { |k,v| nil }).to eq subject + it "returns the instance" do + subject.data["waldo"] = "fred" + subject.data["plugh"] = "xyzzy" + expect(subject.each { |k, v| nil }).to eq subject end - it 'loops as expected' do - subject.data['wibble'] = 'foo' - subject.data['waldo'] = 'fred' - subject.data['plugh'] = 'xyzzy' + it "loops as expected" do + subject.data["wibble"] = "foo" + subject.data["waldo"] = "fred" + subject.data["plugh"] = "xyzzy" capped_keys = [] - subject.each { |k,v| capped_keys << k.capitalize } - expect(capped_keys).to eq ['Wibble', 'Waldo', 'Plugh'] + subject.each { |k, v| capped_keys << k.capitalize } + expect(capped_keys).to eq ["Wibble", "Waldo", "Plugh"] end - it 'returns an enumerator if no block is supplied' do - subject['wibble'] = 'foo' - subject['waldo'] = 'fred' - subject['plugh'] = 'xyzzy' + it "returns an enumerator if no block is supplied" do + subject["wibble"] = "foo" + subject["waldo"] = "fred" + subject["plugh"] = "xyzzy" expect(subject.delete_if).to be_a Enumerator end end - describe '#each_key' do - it 'yields' do - subject['plugh'] = 'xyzzy' + describe "#each_key" do + it "yields" do + subject["plugh"] = "xyzzy" expect { |b| subject.each_key(&b) }.to yield_with_args end - it 'returns the instance' do - subject.data['waldo'] = 'fred' - subject.data['plugh'] = 'xyzzy' + it "returns the instance" do + subject.data["waldo"] = "fred" + subject.data["plugh"] = "xyzzy" expect(subject.each_key { |k| nil }).to eq subject end - it 'loops as expected' do - subject['wibble'] = 'foo' - subject['waldo'] = 'fred' - subject['plugh'] = 'xyzzy' + it "loops as expected" do + subject["wibble"] = "foo" + subject["waldo"] = "fred" + subject["plugh"] = "xyzzy" key_accumulator = [] subject.each_key { |k| key_accumulator << k } - expect(key_accumulator).to eq ['wibble', 'waldo', 'plugh'] + expect(key_accumulator).to eq ["wibble", "waldo", "plugh"] end - it 'returns an enumerator if no block is supplied' do - subject['wibble'] = 'foo' - subject['waldo'] = 'fred' - subject['plugh'] = 'xyzzy' + it "returns an enumerator if no block is supplied" do + subject["wibble"] = "foo" + subject["waldo"] = "fred" + subject["plugh"] = "xyzzy" expect(subject.each_key).to be_a Enumerator end end - describe '#each_value' do - it 'yields' do - subject['plugh'] = 'xyzzy' + describe "#each_value" do + it "yields" do + subject["plugh"] = "xyzzy" expect { |b| subject.each_value(&b) }.to yield_with_args end - it 'returns the instance' do - subject.data['waldo'] = 'fred' - subject.data['plugh'] = 'xyzzy' + it "returns the instance" do + subject.data["waldo"] = "fred" + subject.data["plugh"] = "xyzzy" expect(subject.each_value { |v| nil }).to eq subject end - it 'loops as expected' do - subject['wibble'] = 'foo' - subject['waldo'] = 'fred' - subject['plugh'] = 'xyzzy' + it "loops as expected" do + subject["wibble"] = "foo" + subject["waldo"] = "fred" + subject["plugh"] = "xyzzy" value_accumulator = [] subject.each_value { |v| value_accumulator << v } - expect(value_accumulator).to eq ['foo', 'fred', 'xyzzy'] + expect(value_accumulator).to eq ["foo", "fred", "xyzzy"] end - it 'returns an enumerator if no block is supplied' do - subject['wibble'] = 'foo' - subject['waldo'] = 'fred' - subject['plugh'] = 'xyzzy' + it "returns an enumerator if no block is supplied" do + subject["wibble"] = "foo" + subject["waldo"] = "fred" + subject["plugh"] = "xyzzy" expect(subject.each_value).to be_a Enumerator end - end - describe '#empty' do - it 'returns true when there are no entries' do + describe "#empty" do + it "returns true when there are no entries" do expect(subject.empty?).to be_truthy end - it 'returns false when we have data' do - subject['waldo'] = 'fred' + it "returns false when we have data" do + subject["waldo"] = "fred" expect(subject.empty?).to be_falsey end end - describe '#fetch' do - it 'retrieves the expected value' do - subject['wibble'] = 'wobble' - subject['wubble'] = 'fred' - expect(subject.fetch('wibble')).to eq 'wobble' - end - it 'returns the default if the key is not found and one is supplied' do - subject['wibble'] = 'wobble' - subject['wubble'] = 'fred' - expect(subject.fetch('flob', 'waldo')).to eq 'waldo' - end - it 'raises a KeyError if the key is not found and no default is supplied' do - expect { subject.fetch('flob') }.to raise_error KeyError - end - it 'can take a block as well' do - subject['wibble'] = 'wobble' - subject['wubble'] = 'fred' - expect(subject.fetch('wubble') {|e| e.capitalize }).to eq 'fred' # value takes precence - expect { |b| subject.fetch('foo', &b) }.to yield_with_args - expect(subject.fetch('foo') {|e| e.reverse }).to eq 'oof' + describe "#fetch" do + it "retrieves the expected value" do + subject["wibble"] = "wobble" + subject["wubble"] = "fred" + expect(subject.fetch("wibble")).to eq "wobble" + end + it "returns the default if the key is not found and one is supplied" do + subject["wibble"] = "wobble" + subject["wubble"] = "fred" + expect(subject.fetch("flob", "waldo")).to eq "waldo" + end + it "raises a KeyError if the key is not found and no default is supplied" do + expect { subject.fetch("flob") }.to raise_error KeyError + end + it "can take a block as well" do + subject["wibble"] = "wobble" + subject["wubble"] = "fred" + expect(subject.fetch("wubble") { |e| e.capitalize }).to eq "fred" # value takes precence + expect { |b| subject.fetch("foo", &b) }.to yield_with_args + expect(subject.fetch("foo") { |e| e.reverse }).to eq "oof" end end - describe '#has_key? (and aliases)' do - it 'is true when the key exists' do - subject['wibble'] = 'wobble' - expect(subject.has_key? 'wibble').to be_truthy + describe "#has_key? (and aliases)" do + it "is true when the key exists" do + subject["wibble"] = "wobble" + expect(subject.has_key?("wibble")).to be_truthy end - it 'is false when the key does not exist' do - expect(subject.has_key? 'wibble').to be_falsey + it "is false when the key does not exist" do + expect(subject.has_key?("wibble")).to be_falsey end end - describe '#has_value? (and aliases)' do - it 'is true when the value exists' do - subject['wibble'] = 'wobble' - expect(subject.has_value? 'wobble').to be_truthy + describe "#has_value? (and aliases)" do + it "is true when the value exists" do + subject["wibble"] = "wobble" + expect(subject.has_value?("wobble")).to be_truthy end - it 'is false when the value does not exist' do - expect(subject.has_value? 'wobble').to be_falsey + it "is false when the value does not exist" do + expect(subject.has_value?("wobble")).to be_falsey end end - describe '#keep_if' do - it 'can take a block' do - subject['wibble'] = 'foo' - subject['waldo'] = 'fred' - subject['plugh'] = 'xyzzy' - expect { |b| subject.keep_if(&b) }.to yield_successive_args(['wibble', 'foo'], ['waldo', 'fred'], ['plugh', 'xyzzy']) - end - it 'returns the instance' do - subject['wibble'] = 'foo' - subject['waldo'] = 'fred' - subject['plugh'] = 'xyzzy' - expect( subject.keep_if { |k,v| k.start_with?('w') } ).to eq subject - end - it 'works' do - subject['wibble'] = 'foo' - subject['waldo'] = 'fred' - subject['plugh'] = 'xyzzy' - subject.keep_if { |k,v| k.start_with?('w') } - expect(subject.data).to eq({'wibble'=>'foo', 'waldo'=>'fred'}) + describe "#keep_if" do + it "can take a block" do + subject["wibble"] = "foo" + subject["waldo"] = "fred" + subject["plugh"] = "xyzzy" + expect { |b| subject.keep_if(&b) }.to yield_successive_args(["wibble", "foo"], ["waldo", "fred"], ["plugh", "xyzzy"]) + end + it "returns the instance" do + subject["wibble"] = "foo" + subject["waldo"] = "fred" + subject["plugh"] = "xyzzy" + expect(subject.keep_if { |k, v| k.start_with?("w") }).to eq subject + end + it "works" do + subject["wibble"] = "foo" + subject["waldo"] = "fred" + subject["plugh"] = "xyzzy" + subject.keep_if { |k, v| k.start_with?("w") } + expect(subject.data).to eq({"wibble" => "foo", "waldo" => "fred"}) end end - describe '#key' do - it 'is the key associated with a value' do - subject['thud'] = 'wibble' - subject['plugh'] = 'wobble' - expect(subject.key 'wibble').to eq 'thud' - expect(subject.key 'wobble').to eq 'plugh' - end - it 'is nil if the value is not found' do - subject['thud'] = 'wibble' - subject['plugh'] = 'wobble' - expect(subject.key 'foo').to be_nil + describe "#key" do + it "is the key associated with a value" do + subject["thud"] = "wibble" + subject["plugh"] = "wobble" + expect(subject.key("wibble")).to eq "thud" + expect(subject.key("wobble")).to eq "plugh" + end + it "is nil if the value is not found" do + subject["thud"] = "wibble" + subject["plugh"] = "wobble" + expect(subject.key("foo")).to be_nil end end - describe '#keys' do - it 'is an array of all of the keys in the object' do - subject['foo'] = 'bar' - subject['waldo'] = 'fred' - subject['plugh'] = 'xyzzy' - expect(subject.keys).to eq ['foo', 'waldo', 'plugh'] + describe "#keys" do + it "is an array of all of the keys in the object" do + subject["foo"] = "bar" + subject["waldo"] = "fred" + subject["plugh"] = "xyzzy" + expect(subject.keys).to eq ["foo", "waldo", "plugh"] end end - describe '#length' do - it 'works' do - subject['wibble'] = 'foo' - subject['waldo'] = 'fred' + describe "#length" do + it "works" do + subject["wibble"] = "foo" + subject["waldo"] = "fred" expect(subject.length).to eq 2 end end - describe '#merge' do - it 'returns a new instance of the calling class' do - subject['wibble'] = 'foo' + describe "#merge" do + it "returns a new instance of the calling class" do + subject["wibble"] = "foo" another = hash_like_class.new - another['waldo'] = 'fred' + another["waldo"] = "fred" merged = subject.merge(another) # clear them all to confirm we're not testing equality of anything other # than that we have different instances @@ -318,33 +317,33 @@ def initialize() # new_instance = subject.merge(another) # expect(new_instance.data.last).to eq ['waldo', 'fred'] # end - it 'retains the index position for existing entries, replacing the value' do - subject['wibble'] = 'foo' - subject['plugh'] = 'xyzzy' - subject['foo'] = 'bar' + it "retains the index position for existing entries, replacing the value" do + subject["wibble"] = "foo" + subject["plugh"] = "xyzzy" + subject["foo"] = "bar" another = hash_like_class.new - another['plugh'] = 'fred' + another["plugh"] = "fred" new_instance = subject.merge(another) - expect(new_instance['plugh']).to eq 'fred' - expect(new_instance[new_instance.keys[1]]).to eq 'fred' + expect(new_instance["plugh"]).to eq "fred" + expect(new_instance[new_instance.keys[1]]).to eq "fred" end - it 'takes a block' do - subject['wibble'] = 'foo' - subject['plugh'] = 'xyzzy' - subject['foo'] = 'bar' + it "takes a block" do + subject["wibble"] = "foo" + subject["plugh"] = "xyzzy" + subject["foo"] = "bar" another = hash_like_class.new - another['plugh'] = 'fred' + another["plugh"] = "fred" # e.g. give a block that turns common keys into an Array - new_instance = subject.merge(another) { |k, old_val,new_val| [old_val, new_val] } - expect(new_instance['wibble']).to eq 'foo' - expect(new_instance['plugh']).to eq ['xyzzy', 'fred'] - expect(new_instance['foo']).to eq 'bar' - expect(new_instance.data).to eq({'wibble'=>'foo', 'plugh'=>['xyzzy', 'fred'], 'foo'=>'bar'}) - end - describe 'takes anything that implements `#each { |k,v| block }` and #has_key?' do - it 'returns a new instance of the calling class' do - subject['wibble'] = 'foo' - another = {'waldo' => 'fred'} + new_instance = subject.merge(another) { |k, old_val, new_val| [old_val, new_val] } + expect(new_instance["wibble"]).to eq "foo" + expect(new_instance["plugh"]).to eq ["xyzzy", "fred"] + expect(new_instance["foo"]).to eq "bar" + expect(new_instance.data).to eq({"wibble" => "foo", "plugh" => ["xyzzy", "fred"], "foo" => "bar"}) + end + describe "takes anything that implements `#each { |k,v| block }` and #has_key?" do + it "returns a new instance of the calling class" do + subject["wibble"] = "foo" + another = {"waldo" => "fred"} merged = subject.merge(another) # clear them all to confirm we're not testing equality of anything other # than that we have different instances @@ -362,208 +361,206 @@ def initialize() # new_instance = subject.merge(another) # expect(new_instance.data.last).to eq ['waldo', 'fred'] # end - it 'retains the index position for existing entries, replacing the value' do - subject['wibble'] = 'foo' - subject['plugh'] = 'xyzzy' - subject['foo'] = 'bar' - another = {'plugh' => 'fred' } - another['plugh'] = 'fred' + it "retains the index position for existing entries, replacing the value" do + subject["wibble"] = "foo" + subject["plugh"] = "xyzzy" + subject["foo"] = "bar" + another = {"plugh" => "fred"} + another["plugh"] = "fred" new_instance = subject.merge(another) - expect(new_instance['plugh']).to eq 'fred' - expect(new_instance[new_instance.keys[1]]).to eq 'fred' + expect(new_instance["plugh"]).to eq "fred" + expect(new_instance[new_instance.keys[1]]).to eq "fred" end - it 'takes a block' do - subject['wibble'] = 'foo' - subject['plugh'] = 'xyzzy' - subject['foo'] = 'bar' - another = {'plugh' => 'fred'} + it "takes a block" do + subject["wibble"] = "foo" + subject["plugh"] = "xyzzy" + subject["foo"] = "bar" + another = {"plugh" => "fred"} # e.g. give a block that turns common keys into an Array - new_instance = subject.merge(another) { |k, old_val,new_val| [old_val, new_val] } - expect(new_instance['wibble']).to eq 'foo' - expect(new_instance['plugh']).to eq ['xyzzy', 'fred'] - expect(new_instance['foo']).to eq 'bar' - expect(new_instance.data).to eq({'wibble'=>'foo', 'plugh'=>['xyzzy', 'fred'], 'foo'=>'bar'}) + new_instance = subject.merge(another) { |k, old_val, new_val| [old_val, new_val] } + expect(new_instance["wibble"]).to eq "foo" + expect(new_instance["plugh"]).to eq ["xyzzy", "fred"] + expect(new_instance["foo"]).to eq "bar" + expect(new_instance.data).to eq({"wibble" => "foo", "plugh" => ["xyzzy", "fred"], "foo" => "bar"}) end end end - describe '#merge!' do - it 'returns the instance on which is was called' do - subject['wibble'] = 'foo' + describe "#merge!" do + it "returns the instance on which is was called" do + subject["wibble"] = "foo" another = hash_like_class.new - another['waldo'] = 'fred' + another["waldo"] = "fred" expect(subject.merge!(another)).to eq subject # same instance end - it 'adds new entries to the end' do - subject['wibble'] = 'foo' - subject['plugh'] = 'xyzzy' + it "adds new entries to the end" do + subject["wibble"] = "foo" + subject["plugh"] = "xyzzy" another = hash_like_class.new - another['waldo'] = 'fred' + another["waldo"] = "fred" subject.merge!(another) - expect(subject.data[subject.data.keys.last]).to eq 'fred' + expect(subject.data[subject.data.keys.last]).to eq "fred" end - it 'retains the index position for existing entries, replacing the value' do - subject['wibble'] = 'foo' - subject['plugh'] = 'xyzzy' - subject['foo'] = 'bar' + it "retains the index position for existing entries, replacing the value" do + subject["wibble"] = "foo" + subject["plugh"] = "xyzzy" + subject["foo"] = "bar" another = hash_like_class.new - another['plugh'] = 'fred' + another["plugh"] = "fred" subject.merge!(another) - expect(subject['plugh']).to eq 'fred' - expect(subject.data[subject.keys[1]]).to eq 'fred' + expect(subject["plugh"]).to eq "fred" + expect(subject.data[subject.keys[1]]).to eq "fred" end - it 'takes a block' do - subject['wibble'] = 'foo' - subject['plugh'] = 'xyzzy' - subject['foo'] = 'bar' + it "takes a block" do + subject["wibble"] = "foo" + subject["plugh"] = "xyzzy" + subject["foo"] = "bar" another = hash_like_class.new - another['plugh'] = 'fred' + another["plugh"] = "fred" # e.g. give a block that turns common keys into an Array - subject.merge!(another) { |k, old_val,new_val| [old_val, new_val] } - expect(subject['wibble']).to eq 'foo' - expect(subject['plugh']).to eq ['xyzzy', 'fred'] - expect(subject['foo']).to eq 'bar' - expect(subject.data).to eq({'wibble'=>'foo', 'plugh'=>['xyzzy', 'fred'], 'foo'=>'bar'}) - end - describe 'takes anything that implements `#each { |k,v| block }` and #has_key?' do - it 'returns a new instance of the calling class' do - subject['wibble'] = 'foo' - another = {'waldo' => 'fred'} + subject.merge!(another) { |k, old_val, new_val| [old_val, new_val] } + expect(subject["wibble"]).to eq "foo" + expect(subject["plugh"]).to eq ["xyzzy", "fred"] + expect(subject["foo"]).to eq "bar" + expect(subject.data).to eq({"wibble" => "foo", "plugh" => ["xyzzy", "fred"], "foo" => "bar"}) + end + describe "takes anything that implements `#each { |k,v| block }` and #has_key?" do + it "returns a new instance of the calling class" do + subject["wibble"] = "foo" + another = {"waldo" => "fred"} expect(subject.merge!(another)).to eq subject # same instance end - it 'adds new entries to the end' do - subject['wibble'] = 'foo' - subject['plugh'] = 'xyzzy' - another = {'waldo' => 'fred'} + it "adds new entries to the end" do + subject["wibble"] = "foo" + subject["plugh"] = "xyzzy" + another = {"waldo" => "fred"} subject.merge!(another) - expect(subject.data[subject.data.keys.last]).to eq 'fred' + expect(subject.data[subject.data.keys.last]).to eq "fred" end - it 'retains the index position for existing entries, replacing the value' do - subject['wibble'] = 'foo' - subject['plugh'] = 'xyzzy' - subject['foo'] = 'bar' - another = {'plugh' => 'fred' } + it "retains the index position for existing entries, replacing the value" do + subject["wibble"] = "foo" + subject["plugh"] = "xyzzy" + subject["foo"] = "bar" + another = {"plugh" => "fred"} subject.merge!(another) - expect(subject['plugh']).to eq 'fred' - expect(subject.data[subject.keys[1]]).to eq 'fred' + expect(subject["plugh"]).to eq "fred" + expect(subject.data[subject.keys[1]]).to eq "fred" end - it 'takes a block' do - subject['wibble'] = 'foo' - subject['plugh'] = 'xyzzy' - subject['foo'] = 'bar' - another = {'plugh' => 'fred'} - subject.merge!(another) { |k, old_val,new_val| "#{k}, #{old_val}, #{new_val}" } - expect(subject['wibble']).to eq 'foo' - expect(subject['plugh']).to eq 'plugh, xyzzy, fred' - expect(subject['foo']).to eq 'bar' - expect(subject.data).to eq({'wibble'=>'foo', 'plugh'=>'plugh, xyzzy, fred', 'foo'=>'bar'}) + it "takes a block" do + subject["wibble"] = "foo" + subject["plugh"] = "xyzzy" + subject["foo"] = "bar" + another = {"plugh" => "fred"} + subject.merge!(another) { |k, old_val, new_val| "#{k}, #{old_val}, #{new_val}" } + expect(subject["wibble"]).to eq "foo" + expect(subject["plugh"]).to eq "plugh, xyzzy, fred" + expect(subject["foo"]).to eq "bar" + expect(subject.data).to eq({"wibble" => "foo", "plugh" => "plugh, xyzzy, fred", "foo" => "bar"}) end end end - describe '#reject!' do - it 'can take a block' do - subject['wibble'] = 'foo' - subject['waldo'] = 'fred' - subject['plugh'] = 'xyzzy' - expect { |b| subject.reject!(&b) }.to yield_successive_args(['wibble', 'foo'], ['waldo', 'fred'], ['plugh', 'xyzzy']) - end - it 'returns the instance if there were changes' do - subject['wibble'] = 'foo' - subject['waldo'] = 'fred' - subject['plugh'] = 'xyzzy' - expect( subject.reject! { |k| k.start_with?('w') } ).to be subject - end - it 'returns nil if there were no changes' do - subject['wibble'] = 'foo' - subject['waldo'] = 'fred' - subject['plugh'] = 'xyzzy' - expect( subject.reject! { |k| k.start_with?('X') } ).to be_nil - end - it 'works' do - subject['wibble'] = 'foo' - subject['waldo'] = 'fred' - subject['plugh'] = 'xyzzy' - subject.reject! { |k| k.start_with?('w') } - expect(subject.data).to eq({'plugh' => 'xyzzy'}) + describe "#reject!" do + it "can take a block" do + subject["wibble"] = "foo" + subject["waldo"] = "fred" + subject["plugh"] = "xyzzy" + expect { |b| subject.reject!(&b) }.to yield_successive_args(["wibble", "foo"], ["waldo", "fred"], ["plugh", "xyzzy"]) + end + it "returns the instance if there were changes" do + subject["wibble"] = "foo" + subject["waldo"] = "fred" + subject["plugh"] = "xyzzy" + expect(subject.reject! { |k| k.start_with?("w") }).to be subject + end + it "returns nil if there were no changes" do + subject["wibble"] = "foo" + subject["waldo"] = "fred" + subject["plugh"] = "xyzzy" + expect(subject.reject! { |k| k.start_with?("X") }).to be_nil + end + it "works" do + subject["wibble"] = "foo" + subject["waldo"] = "fred" + subject["plugh"] = "xyzzy" + subject.reject! { |k| k.start_with?("w") } + expect(subject.data).to eq({"plugh" => "xyzzy"}) end end - describe '#select' do - it 'yields' do - subject['thud'] = 'wibble' - subject['plugh'] = 'wobble' - subject['waldo'] = 'fred' - expect { |b| subject.select(&b) }.to yield_successive_args(['thud', 'wibble'], ['plugh', 'wobble'], ['waldo', 'fred']) - end - it 'returns a new instance of the class' do - subject['thud'] = 'wibble' - subject['plugh'] = 'wobble' - subject['waldo'] = 'fred' - expect( subject.select{ |k,v| true }.class ).to eq subject.class - expect( subject.select{ |k,v| true } ).to_not eq subject - end - it 'selects but doesn\'t delete from the original instance' do - subject['thud'] = 'wibble' - subject['plugh'] = 'wobble' - subject['waldo'] = 'fred' - expect( subject.select{ |k,v| k.include?('u') }.data ).to eq({'thud'=>'wibble', 'plugh'=>'wobble'}) - expect( subject.data ).to eq subject.data + describe "#select" do + it "yields" do + subject["thud"] = "wibble" + subject["plugh"] = "wobble" + subject["waldo"] = "fred" + expect { |b| subject.select(&b) }.to yield_successive_args(["thud", "wibble"], ["plugh", "wobble"], ["waldo", "fred"]) + end + it "returns a new instance of the class" do + subject["thud"] = "wibble" + subject["plugh"] = "wobble" + subject["waldo"] = "fred" + expect(subject.select { |k, v| true }.class).to eq subject.class + expect(subject.select { |k, v| true }).to_not eq subject + end + it "selects but doesn't delete from the original instance" do + subject["thud"] = "wibble" + subject["plugh"] = "wobble" + subject["waldo"] = "fred" + expect(subject.select { |k, v| k.include?("u") }.data).to eq({"thud" => "wibble", "plugh" => "wobble"}) + expect(subject.data).to eq subject.data end end - describe '#select!' do - it 'can take a block' do - subject['wibble'] = 'foo' - subject['waldo'] = 'fred' - subject['plugh'] = 'xyzzy' - expect { |b| subject.select!(&b) }.to yield_successive_args(['wibble', 'foo'], ['waldo', 'fred'], ['plugh', 'xyzzy']) - end - it 'returns nil if there were no changes' do - subject['wibble'] = 'foo' - subject['waldo'] = 'fred' - subject['wobble'] = 'xyzzy' - expect( subject.select! { |k,v| k.start_with?('w') } ).to be_nil - end - it 'returns the instance if there were changes' do - subject['wibble'] = 'foo' - subject['waldo'] = 'fred' - subject['plugh'] = 'xyzzy' - expect( subject.select! { |k,v| k.start_with?('w') } ).to eq subject - end - it 'works' do - subject['wibble'] = 'foo' - subject['waldo'] = 'fred' - subject['plugh'] = 'xyzzy' - subject.select! { |k,v| k.start_with?('p') } - expect(subject.data).to eq({'plugh' => 'xyzzy'}) + describe "#select!" do + it "can take a block" do + subject["wibble"] = "foo" + subject["waldo"] = "fred" + subject["plugh"] = "xyzzy" + expect { |b| subject.select!(&b) }.to yield_successive_args(["wibble", "foo"], ["waldo", "fred"], ["plugh", "xyzzy"]) + end + it "returns nil if there were no changes" do + subject["wibble"] = "foo" + subject["waldo"] = "fred" + subject["wobble"] = "xyzzy" + expect(subject.select! { |k, v| k.start_with?("w") }).to be_nil + end + it "returns the instance if there were changes" do + subject["wibble"] = "foo" + subject["waldo"] = "fred" + subject["plugh"] = "xyzzy" + expect(subject.select! { |k, v| k.start_with?("w") }).to eq subject + end + it "works" do + subject["wibble"] = "foo" + subject["waldo"] = "fred" + subject["plugh"] = "xyzzy" + subject.select! { |k, v| k.start_with?("p") } + expect(subject.data).to eq({"plugh" => "xyzzy"}) end end - describe '#shift' do - it 'returns the first element in the hash without a param' do - subject['thud'] = 'wibble' - subject['plugh'] = 'wobble' - expect(subject.shift).to eq ['thud','wibble'] - expect(subject.data).to eq({'plugh' => 'wobble'}) + describe "#shift" do + it "returns the first element in the hash without a param" do + subject["thud"] = "wibble" + subject["plugh"] = "wobble" + expect(subject.shift).to eq ["thud", "wibble"] + expect(subject.data).to eq({"plugh" => "wobble"}) end end - describe 'store' do - it 'works as an alias for []=' do - subject.store('foo', 'bar') - expect(subject.data).to eq({'foo' => 'bar'}) + describe "store" do + it "works as an alias for []=" do + subject.store("foo", "bar") + expect(subject.data).to eq({"foo" => "bar"}) end end - describe '#values' do - it 'is an array of all of the keys in the object' do - subject['foo'] = 'bar' - subject['waldo'] = 'fred' - subject['plugh'] = 'xyzzy' - expect(subject.values).to eq ['bar', 'fred', 'xyzzy'] + describe "#values" do + it "is an array of all of the keys in the object" do + subject["foo"] = "bar" + subject["waldo"] = "fred" + subject["plugh"] = "xyzzy" + expect(subject.values).to eq ["bar", "fred", "xyzzy"] end end - end - diff --git a/spec/unit/iiif/ordered_hash_spec.rb b/spec/unit/iiif/ordered_hash_spec.rb index 5cab952..49b88a4 100644 --- a/spec/unit/iiif/ordered_hash_spec.rb +++ b/spec/unit/iiif/ordered_hash_spec.rb @@ -1,155 +1,150 @@ describe IIIF::OrderedHash do - - describe '#camelize_keys' do + describe "#camelize_keys" do before(:each) do - @uri = 'http://www.example.org/descriptions/book1.xml' - @within_uri = 'http://www.example.org/collections/books/' - subject['see_also'] = @uri - subject['within'] = @within_uri + @uri = "http://www.example.org/descriptions/book1.xml" + @within_uri = "http://www.example.org/collections/books/" + subject["see_also"] = @uri + subject["within"] = @within_uri end - it 'changes snake_case keys to camelCase' do + it "changes snake_case keys to camelCase" do subject.camelize_keys # #send gets past protection - expect(subject.keys.include?('seeAlso')).to be_truthy - expect(subject.keys.include?('see_also')).to be_falsey + expect(subject.key?("seeAlso")).to be_truthy + expect(subject.key?("see_also")).to be_falsey end - it 'keeps the right values' do + it "keeps the right values" do subject.camelize_keys - expect(subject['seeAlso']).to eq @uri - expect(subject['within']).to eq @within_uri + expect(subject["seeAlso"]).to eq @uri + expect(subject["within"]).to eq @within_uri end - it 'keeps things in the same position' do - see_also_position = subject.keys.index('see_also') - within_position = subject.keys.index('within') + it "keeps things in the same position" do + see_also_position = subject.keys.index("see_also") + within_position = subject.keys.index("within") subject.camelize_keys - expect(subject.keys[see_also_position]).to eq 'seeAlso' - expect(subject.keys[within_position]).to eq 'within' + expect(subject.keys[see_also_position]).to eq "seeAlso" + expect(subject.keys[within_position]).to eq "within" end - end - describe '#snakeize_keys' do + describe "#snakeize_keys" do before(:each) do - @uri = 'http://www.example.org/descriptions/book1.xml' - @within_uri = 'http://www.example.org/collections/books/' - subject['seeAlso'] = @uri - subject['within'] = @within_uri + @uri = "http://www.example.org/descriptions/book1.xml" + @within_uri = "http://www.example.org/collections/books/" + subject["seeAlso"] = @uri + subject["within"] = @within_uri end - it 'changes camelCase keys to snake_case' do + it "changes camelCase keys to snake_case" do subject.snakeize_keys - expect(subject.keys.include?('see_also')).to be_truthy - expect(subject.keys.include?('seeAlso')).to be_falsey + expect(subject.key?("see_also")).to be_truthy + expect(subject.key?("seeAlso")).to be_falsey end - it 'keeps the right values' do + it "keeps the right values" do subject.snakeize_keys - expect(subject['see_also']).to eq @uri - expect(subject['within']).to eq @within_uri + expect(subject["see_also"]).to eq @uri + expect(subject["within"]).to eq @within_uri end - it 'keeps things in the same position' do - see_also_position = subject.keys.index('seeAlso') - within_position = subject.keys.index('within') + it "keeps things in the same position" do + see_also_position = subject.keys.index("seeAlso") + within_position = subject.keys.index("within") subject.snakeize_keys - expect(subject.keys[see_also_position]).to eq 'see_also' - expect(subject.keys[within_position]).to eq 'within' + expect(subject.keys[see_also_position]).to eq "see_also" + expect(subject.keys[within_position]).to eq "within" end end - describe 'insertion patches' do + describe "insertion patches" do + let(:init_data) { [["wubble", "fred"], ["baz", "qux"], ["grault", "garply"]] } - let (:init_data) { [ ['wubble', 'fred'], ['baz', 'qux'], ['grault','garply'] ] } - - subject do + subject do hsh = described_class.new init_data.each { |e| hsh[e[0]] = e[1] } hsh end - describe '#insert' do - it 'inserts as expected' do - subject.insert(2, 'quux', 'corge') - expect(subject[subject.keys[0]]).to eq 'fred' - expect(subject[subject.keys[1]]).to eq 'qux' - expect(subject[subject.keys[2]]).to eq 'corge' - expect(subject[subject.keys[3]]).to eq 'garply' + describe "#insert" do + it "inserts as expected" do + subject.insert(2, "quux", "corge") + expect(subject[subject.keys[0]]).to eq "fred" + expect(subject[subject.keys[1]]).to eq "qux" + expect(subject[subject.keys[2]]).to eq "corge" + expect(subject[subject.keys[3]]).to eq "garply" end - it 'returns the instance' do - expect(subject.insert(1, 'quux','corge')).to eq subject + it "returns the instance" do + expect(subject.insert(1, "quux", "corge")).to eq subject end - it 'raises IndexError if a negative index is too small' do - expect { subject.insert(-5, 'quux','corge') }.to raise_error IndexError + it "raises IndexError if a negative index is too small" do + expect { subject.insert(-5, "quux", "corge") }.to raise_error IndexError end - it 'puts index -1 on the end' do - subject.insert(-1, 'thud','wibble') - expect(subject[subject.keys.last]).to eq 'wibble' + it "puts index -1 on the end" do + subject.insert(-1, "thud", "wibble") + expect(subject[subject.keys.last]).to eq "wibble" end end - describe '#insert_before' do - it 'inserts in the expected place with a supplied key' do - subject.insert_before(existing_key: 'grault', new_key: 'quux', value: 'corge') - expect(subject.keys).to eq ['wubble','baz','quux','grault'] + describe "#insert_before" do + it "inserts in the expected place with a supplied key" do + subject.insert_before(existing_key: "grault", new_key: "quux", value: "corge") + expect(subject.keys).to eq ["wubble", "baz", "quux", "grault"] end - it 'inserts in the expected place with a supplied block' do - subject.insert_before(new_key: 'quux', value: 'corge') { |k,v| k.start_with?('g') } - expect(subject.keys).to eq ['wubble','baz','quux','grault'] + it "inserts in the expected place with a supplied block" do + subject.insert_before(new_key: "quux", value: "corge") { |k, v| k.start_with?("g") } + expect(subject.keys).to eq ["wubble", "baz", "quux", "grault"] end - it 'returns the instance' do - expect(subject.insert_before(existing_key: 'grault', new_key: 'quux', value: 'corge')).to be subject + it "returns the instance" do + expect(subject.insert_before(existing_key: "grault", new_key: "quux", value: "corge")).to be subject end - describe 'raises KeyError' do - it 'when the supplied existing key is not found' do - expect { subject.insert_before(existing_key: 'foo', new_key: 'quux', value: 'corge') }.to raise_error KeyError + describe "raises KeyError" do + it "when the supplied existing key is not found" do + expect { subject.insert_before(existing_key: "foo", new_key: "quux", value: "corge") }.to raise_error KeyError end - it 'when the supplied new key already exists' do - expect { subject.insert_before(existing_key: 'grault', new_key: 'wubble', value: 'corge') }.to raise_error KeyError + it "when the supplied new key already exists" do + expect { subject.insert_before(existing_key: "grault", new_key: "wubble", value: "corge") }.to raise_error KeyError end end end - describe '#insert_after' do - it 'inserts in the expected place with a supplied key' do - subject.insert_after(existing_key: 'baz', new_key: 'quux', value: 'corge') - expect(subject.keys).to eq ['wubble','baz','quux','grault'] + describe "#insert_after" do + it "inserts in the expected place with a supplied key" do + subject.insert_after(existing_key: "baz", new_key: "quux", value: "corge") + expect(subject.keys).to eq ["wubble", "baz", "quux", "grault"] end - it 'inserts in the expected place with a supplied block' do - subject.insert_after(new_key: 'quux', value: 'corge') { |k,v| k.start_with?('g') } - expect(subject.keys).to eq ['wubble','baz','quux','grault'] + it "inserts in the expected place with a supplied block" do + subject.insert_after(new_key: "quux", value: "corge") { |k, v| k.start_with?("g") } + expect(subject.keys).to eq ["wubble", "baz", "quux", "grault"] end - it 'returns the instance' do - expect(subject.insert_after(existing_key: 'baz', new_key: 'quux', value: 'corge')).to be subject + it "returns the instance" do + expect(subject.insert_after(existing_key: "baz", new_key: "quux", value: "corge")).to be subject end - describe 'raises KeyError' do - it 'when the supplied existing key is not found' do - expect { subject.insert_after(existing_key: 'foo', new_key: 'quux', value: 'corge') }.to raise_error KeyError + describe "raises KeyError" do + it "when the supplied existing key is not found" do + expect { subject.insert_after(existing_key: "foo", new_key: "quux", value: "corge") }.to raise_error KeyError end - it 'when the supplied new key already exists' do - expect { subject.insert_after(existing_key: 'grault', new_key: 'wubble', value: 'corge') }.to raise_error KeyError + it "when the supplied new key already exists" do + expect { subject.insert_after(existing_key: "grault", new_key: "wubble", value: "corge") }.to raise_error KeyError end end end - describe '#unshift' do - it 'adds an entry to the front of the object' do - subject.unshift('thud','wibble') - expect(subject[subject.keys[0]]).to eq 'wibble' + describe "#unshift" do + it "adds an entry to the front of the object" do + subject.unshift("thud", "wibble") + expect(subject[subject.keys[0]]).to eq "wibble" end - it 'returns the instance' do - expect(subject.unshift('thud','wibble')).to be subject + it "returns the instance" do + expect(subject.unshift("thud", "wibble")).to be subject end end - describe '#remove_empties' do - it 'if they\'re arrays' do + describe "#remove_empties" do + it "if they're arrays" do subject[:wubble] = [] subject.remove_empties expect(subject.has_key?(:wubble)).to be_falsey end - it 'if they\'re nil' do + it "if they're nil" do subject[:wubble] = nil subject.remove_empties expect(subject.has_key?(:wubble)).to be_falsey end end - end end - diff --git a/spec/unit/iiif/presentation/abstract_resource_spec.rb b/spec/unit/iiif/presentation/abstract_resource_spec.rb index ec41361..a4fdb65 100644 --- a/spec/unit/iiif/presentation/abstract_resource_spec.rb +++ b/spec/unit/iiif/presentation/abstract_resource_spec.rb @@ -1,133 +1,127 @@ -require 'active_support/inflector' -require 'json' -require File.join(File.dirname(__FILE__), '../../../../lib/iiif/hash_behaviours') - +require "active_support/inflector" +require "json" +require File.join(File.dirname(__FILE__), "../../../../lib/iiif/hash_behaviours") describe IIIF::Presentation::AbstractResource do - - let(:fixtures_dir) { File.join(File.dirname(__FILE__), '../../../fixtures') } - let(:manifest_from_spec_path) { File.join(fixtures_dir, 'manifests/complete_from_spec.json') } + let(:fixtures_dir) { File.join(File.dirname(__FILE__), "../../../fixtures") } + let(:manifest_from_spec_path) { File.join(fixtures_dir, "manifests/complete_from_spec.json") } let(:abstract_resource_subclass) do Class.new(IIIF::Presentation::AbstractResource) do include IIIF::HashBehaviours - def initialize(hsh={}) - hsh['@type'] = 'a:SubClass' unless hsh.has_key?('@type') - super(hsh) + def initialize(hsh = {}) + hsh["@type"] = "a:SubClass" unless hsh.has_key?("@type") + super end def required_keys - super + %w{ @id } + super + %w[@id] end end end subject do - instance = abstract_resource_subclass.new - instance['@id'] = 'http://example.com/prefix/manifest/123' + instance = abstract_resource_subclass.new + instance["@id"] = "http://example.com/prefix/manifest/123" instance end - describe '#initialize' do - it 'raises an error if you try to instantiate AbstractResource' do + describe "#initialize" do + it "raises an error if you try to instantiate AbstractResource" do expect { IIIF::Presentation::AbstractResource.new }.to raise_error(RuntimeError) end - it 'sets @type' do - expect(subject['@type']).to eq 'a:SubClass' + it "sets @type" do + expect(subject["@type"]).to eq "a:SubClass" end - it 'can take any old hash' do + it "can take any old hash" do hsh = JSON.parse(IO.read(manifest_from_spec_path)) new_instance = abstract_resource_subclass.new(hsh) - expect(new_instance['label']).to eq 'Book 1' + expect(new_instance["label"]).to eq "Book 1" end end - describe 'A nested object (e.g. self[\'metdata\'])' do - it 'returns [] if not set' do + describe "A nested object (e.g. self['metdata'])" do + it "returns [] if not set" do expect(subject.metadata).to eq([]) end - it 'is not in #to_ordered_hash at all if we access it but do not append to it' do + it "is not in #to_ordered_hash at all if we access it but do not append to it" do subject.metadata # touch it expect(subject.metadata).to eq([]) - expect(subject.to_ordered_hash.has_key?('metadata')).to be_falsey + expect(subject.to_ordered_hash.has_key?("metadata")).to be_falsey end - it 'gets structured as we\'d expect' do + it "gets structured as we'd expect" do subject.metadata << { - 'label' => 'Author', - 'value' => 'Anne Author' + "label" => "Author", + "value" => "Anne Author" } subject.metadata << { - 'label' => 'Published', - 'value' => [ - {'@value'=> 'Paris, circa 1400', '@language'=>'en'}, - {'@value'=> 'Paris, environ 14eme siecle', '@language'=>'fr'} + "label" => "Published", + "value" => [ + {"@value" => "Paris, circa 1400", "@language" => "en"}, + {"@value" => "Paris, environ 14eme siecle", "@language" => "fr"} ] } - expect(subject.metadata[0]['label']).to eq('Author') - expect(subject.metadata[1]['value'].length).to eq(2) - expect(subject.metadata[1]['value'].select { |e| e['@language'] == 'fr'}.last['@value']).to eq('Paris, environ 14eme siecle') + expect(subject.metadata[0]["label"]).to eq("Author") + expect(subject.metadata[1]["value"].length).to eq(2) + expect(subject.metadata[1]["value"].reverse.find { |e| e["@language"] == "fr" }["@value"]).to eq("Paris, environ 14eme siecle") end - it 'roundtrips' do + it "roundtrips" do subject.metadata << { - 'label' => 'Author', - 'value' => 'Anne Author' + "label" => "Author", + "value" => "Anne Author" } subject.metadata << { - 'label' => 'Published', - 'value' => [ - {'@value'=> 'Paris, circa 1400', '@language'=>'en'}, - {'@value'=> 'Paris, environ 14eme siecle', '@language'=>'fr'} + "label" => "Published", + "value" => [ + {"@value" => "Paris, circa 1400", "@language" => "en"}, + {"@value" => "Paris, environ 14eme siecle", "@language" => "fr"} ] } - File.open('/tmp/osullivan-spec.json','w') do |f| - f.write(subject.to_json) - end - parsed = subject.class.parse('/tmp/osullivan-spec.json') - expect(parsed['metadata'][0]['label']).to eq('Author') - expect(parsed['metadata'][1]['value'].length).to eq(2) - expect(parsed['metadata'][1]['value'].select { |e| e['@language'] == 'fr'}.last['@value']).to eq('Paris, environ 14eme siecle') - File.delete('/tmp/osullivan-spec.json') + File.write("/tmp/osullivan-spec.json", subject.to_json) + parsed = subject.class.parse("/tmp/osullivan-spec.json") + expect(parsed["metadata"][0]["label"]).to eq("Author") + expect(parsed["metadata"][1]["value"].length).to eq(2) + expect(parsed["metadata"][1]["value"].reverse.find { |e| e["@language"] == "fr" }["@value"]).to eq("Paris, environ 14eme siecle") + File.delete("/tmp/osullivan-spec.json") end end - describe '#required_keys' do - it 'accumulates' do - expect(subject.required_keys).to eq %w{ @type @id } + describe "#required_keys" do + it "accumulates" do + expect(subject.required_keys).to eq %w[@type @id] end end - describe '#to_ordered_hash' do - describe 'adds the @context' do - before(:each) { subject.delete('@context') } - it 'by default' do - expect(subject.has_key?('@context')).to be_falsey - expect(subject.to_ordered_hash.has_key?('@context')).to be_truthy + describe "#to_ordered_hash" do + describe "adds the @context" do + before(:each) { subject.delete("@context") } + it "by default" do + expect(subject.has_key?("@context")).to be_falsey + expect(subject.to_ordered_hash.has_key?("@context")).to be_truthy end - it 'unless you say not to' do - expect(subject.has_key?('@context')).to be_falsey - expect(subject.to_ordered_hash(include_context: false).has_key?('@context')).to be_falsey + it "unless you say not to" do + expect(subject.has_key?("@context")).to be_falsey + expect(subject.to_ordered_hash(include_context: false).has_key?("@context")).to be_falsey end - it 'or it\'s already there' do - different_ctxt = 'http://example.org/context' - subject['@context'] = different_ctxt + it "or it's already there" do + different_ctxt = "http://example.org/context" + subject["@context"] = different_ctxt oh = subject.to_ordered_hash - expect(oh['@context']).to eq different_ctxt + expect(oh["@context"]).to eq different_ctxt end end - describe 'runs the validations' do + describe "runs the validations" do # Test this here because there's nothing to validate on the superclass (Subject) let(:error) { IIIF::Presentation::MissingRequiredKeyError } - before(:each) { subject.delete('@id') } - it 'raises exceptions' do + before(:each) { subject.delete("@id") } + it "raises exceptions" do expect { subject.to_ordered_hash }.to raise_error error end - it 'unless you tell it not to' do + it "unless you tell it not to" do expect { subject.to_ordered_hash(force: true) }.to_not raise_error end end end - end - diff --git a/spec/unit/iiif/presentation/annotation_list_spec.rb b/spec/unit/iiif/presentation/annotation_list_spec.rb index 2db64a5..dd32d46 100644 --- a/spec/unit/iiif/presentation/annotation_list_spec.rb +++ b/spec/unit/iiif/presentation/annotation_list_spec.rb @@ -1,7 +1,5 @@ describe IIIF::Presentation::AnnotationList do - describe "#{described_class}.define_methods_for_array_only_keys" do - it_behaves_like 'it has the appropriate methods for array-only keys' + it_behaves_like "it has the appropriate methods for array-only keys" end - end diff --git a/spec/unit/iiif/presentation/annotation_spec.rb b/spec/unit/iiif/presentation/annotation_spec.rb index 5b9881e..4e79bb9 100644 --- a/spec/unit/iiif/presentation/annotation_spec.rb +++ b/spec/unit/iiif/presentation/annotation_spec.rb @@ -1,7 +1,5 @@ describe IIIF::Presentation::Annotation do - describe "#{described_class}.define_methods_for_abstract_resource_only_keys" do - it_behaves_like 'it has the appropriate methods for abstract_resource_only_keys' + it_behaves_like "it has the appropriate methods for abstract_resource_only_keys" end - end diff --git a/spec/unit/iiif/presentation/canvas_spec.rb b/spec/unit/iiif/presentation/canvas_spec.rb index 8f14585..8cea351 100644 --- a/spec/unit/iiif/presentation/canvas_spec.rb +++ b/spec/unit/iiif/presentation/canvas_spec.rb @@ -1,5 +1,4 @@ describe IIIF::Presentation::Canvas do - let(:fixed_values) do { "@context" => "http://iiif.io/api/presentation/2/context.json", @@ -8,38 +7,36 @@ "label" => "p. 1", "height" => 1000, "width" => 750, - "images" => [ ], - "otherContent" => [ ] + "images" => [], + "otherContent" => [] } end - - describe '#initialize' do - it 'sets @type' do - expect(subject['@type']).to eq 'sc:Canvas' + describe "#initialize" do + it "sets @type" do + expect(subject["@type"]).to eq "sc:Canvas" end end describe "#{described_class}.int_only_keys" do - it_behaves_like 'it has the appropriate methods for integer-only keys' + it_behaves_like "it has the appropriate methods for integer-only keys" end describe "#{described_class}.define_methods_for_string_only_keys" do - it_behaves_like 'it has the appropriate methods for string-only keys' + it_behaves_like "it has the appropriate methods for string-only keys" end - + describe "#{described_class}.define_methods_for_array_only_keys" do - it_behaves_like 'it has the appropriate methods for array-only keys' + it_behaves_like "it has the appropriate methods for array-only keys" end describe "#{described_class}.define_methods_for_any_type_keys" do - it_behaves_like 'it has the appropriate methods for any-type keys' + it_behaves_like "it has the appropriate methods for any-type keys" end describe "#legal_viewing_hint_values" do it "should not error" do - expect{subject.legal_viewing_hint_values}.not_to raise_error + expect { subject.legal_viewing_hint_values }.not_to raise_error end end - end diff --git a/spec/unit/iiif/presentation/collection_spec.rb b/spec/unit/iiif/presentation/collection_spec.rb index 4fc1a68..175f4ba 100644 --- a/spec/unit/iiif/presentation/collection_spec.rb +++ b/spec/unit/iiif/presentation/collection_spec.rb @@ -1,54 +1,47 @@ describe IIIF::Presentation::Collection do - - let(:fixed_values) do + let(:fixed_values) do { - '@context' => 'http://iiif.io/api/presentation/2/context.json', - '@id' => 'http://example.org/iiif/collection/top', - '@type' => 'sc:Collection', - 'label' => 'Top Level Collection for Example Organization', - 'description' => 'Description of Collection', - 'attribution' => 'Provided by Example Organization', - - 'collections' => [ - { '@id' => 'http://example.org/iiif/collection/part1', - '@type' => 'sc:Collection', - 'label' => 'Sub Collection 1' - }, - { '@id' => 'http://example.org/iiif/collection/part2', - '@type' => 'sc:Collection', - 'label' => 'Sub Collection 2' - } + "@context" => "http://iiif.io/api/presentation/2/context.json", + "@id" => "http://example.org/iiif/collection/top", + "@type" => "sc:Collection", + "label" => "Top Level Collection for Example Organization", + "description" => "Description of Collection", + "attribution" => "Provided by Example Organization", + + "collections" => [ + {"@id" => "http://example.org/iiif/collection/part1", + "@type" => "sc:Collection", + "label" => "Sub Collection 1"}, + {"@id" => "http://example.org/iiif/collection/part2", + "@type" => "sc:Collection", + "label" => "Sub Collection 2"} ], - 'manifests' => [ - { '@id' => 'http://example.org/iiif/book1/manifest', - '@type' => 'sc:Manifest', - 'label' => 'Book 1' - } + "manifests" => [ + {"@id" => "http://example.org/iiif/book1/manifest", + "@type" => "sc:Manifest", + "label" => "Book 1"} ] } end - describe '#initialize' do - it 'sets @type to sc:Collection by default' do - expect(subject['@type']).to eq 'sc:Collection' + describe "#initialize" do + it "sets @type to sc:Collection by default" do + expect(subject["@type"]).to eq "sc:Collection" end end describe "#{described_class}.define_methods_for_array_only_keys" do - it_behaves_like 'it has the appropriate methods for array-only keys' + it_behaves_like "it has the appropriate methods for array-only keys" end describe "#{described_class}.define_methods_for_string_only_keys" do - it_behaves_like 'it has the appropriate methods for string-only keys' + it_behaves_like "it has the appropriate methods for string-only keys" end describe "#{described_class}.define_methods_for_any_type_keys" do - it_behaves_like 'it has the appropriate methods for any-type keys' + it_behaves_like "it has the appropriate methods for any-type keys" end - describe '#validate' do + describe "#validate" do end - end - - diff --git a/spec/unit/iiif/presentation/image_resource_spec.rb b/spec/unit/iiif/presentation/image_resource_spec.rb index 70013e8..8eb1260 100644 --- a/spec/unit/iiif/presentation/image_resource_spec.rb +++ b/spec/unit/iiif/presentation/image_resource_spec.rb @@ -1,13 +1,11 @@ describe IIIF::Presentation::ImageResource do - - describe '#initialize' do - it 'sets @type to dctypes:Image' do - expect(subject['@type']).to eq 'dctypes:Image' + describe "#initialize" do + it "sets @type to dctypes:Image" do + expect(subject["@type"]).to eq "dctypes:Image" end end describe "#{described_class}.int_only_keys" do - it_behaves_like 'it has the appropriate methods for integer-only keys' + it_behaves_like "it has the appropriate methods for integer-only keys" end - end diff --git a/spec/unit/iiif/presentation/layer_spec.rb b/spec/unit/iiif/presentation/layer_spec.rb index e9da757..1e10a53 100644 --- a/spec/unit/iiif/presentation/layer_spec.rb +++ b/spec/unit/iiif/presentation/layer_spec.rb @@ -1,38 +1,34 @@ describe IIIF::Presentation::Layer do - let(:fixed_values) do { - '@context' => 'http://iiif.io/api/presentation/2/context.json', - '@id' => 'http://www.example.org/iiif/book1/layer/transcription', - '@type' => 'sc:Layer', - 'label' => 'Diplomatic Transcription', - 'otherContent' => [ - 'http://www.example.org/iiif/book1/list/l1', - 'http://www.example.org/iiif/book1/list/l2', - 'http://www.example.org/iiif/book1/list/l3', - 'http://www.example.org/iiif/book1/list/l4' + "@context" => "http://iiif.io/api/presentation/2/context.json", + "@id" => "http://www.example.org/iiif/book1/layer/transcription", + "@type" => "sc:Layer", + "label" => "Diplomatic Transcription", + "otherContent" => [ + "http://www.example.org/iiif/book1/list/l1", + "http://www.example.org/iiif/book1/list/l2", + "http://www.example.org/iiif/book1/list/l3", + "http://www.example.org/iiif/book1/list/l4" ] } end - - describe '#initialize' do - it 'sets @type' do - expect(subject['@type']).to eq 'sc:Layer' + describe "#initialize" do + it "sets @type" do + expect(subject["@type"]).to eq "sc:Layer" end end describe "#{described_class}.define_methods_for_string_only_keys" do - it_behaves_like 'it has the appropriate methods for string-only keys' + it_behaves_like "it has the appropriate methods for string-only keys" end - + describe "#{described_class}.define_methods_for_array_only_keys" do - it_behaves_like 'it has the appropriate methods for array-only keys' + it_behaves_like "it has the appropriate methods for array-only keys" end describe "#{described_class}.define_methods_for_any_type_keys" do - it_behaves_like 'it has the appropriate methods for any-type keys' + it_behaves_like "it has the appropriate methods for any-type keys" end - end - diff --git a/spec/unit/iiif/presentation/manifest_spec.rb b/spec/unit/iiif/presentation/manifest_spec.rb index 3dd5b98..116e10f 100644 --- a/spec/unit/iiif/presentation/manifest_spec.rb +++ b/spec/unit/iiif/presentation/manifest_spec.rb @@ -1,89 +1,86 @@ describe IIIF::Presentation::Manifest do - let(:subclass_subject) do Class.new(IIIF::Presentation::Manifest) do - def initialize(hsh={}) - hsh = { '@type' => 'a:SubClass' } - super(hsh) + def initialize(_hsh = {}) + super({"@type" => "a:SubClass"}) end end end let(:fixed_values) do { - 'type' => 'a:SubClass', - 'id' => 'http://example.com/prefix/manifest/123', - 'context' => IIIF::Presentation::CONTEXT, - 'label' => {'en' => ['Book 1']}, - 'description' => 'A longer description of this example book. It should give some real information.', - 'thumbnail' => { - '@id' => 'http://www.example.org/images/book1-page1/full/80,100/0/default.jpg', - 'service'=> { - '@context' => 'http://iiif.io/api/image/2/context.json', - '@id' => 'http://www.example.org/images/book1-page1', - 'profile' => 'http://iiif.io/api/image/2/level1.json' + "type" => "a:SubClass", + "id" => "http://example.com/prefix/manifest/123", + "context" => IIIF::Presentation::CONTEXT, + "label" => {"en" => ["Book 1"]}, + "description" => "A longer description of this example book. It should give some real information.", + "thumbnail" => { + "@id" => "http://www.example.org/images/book1-page1/full/80,100/0/default.jpg", + "service" => { + "@context" => "http://iiif.io/api/image/2/context.json", + "@id" => "http://www.example.org/images/book1-page1", + "profile" => "http://iiif.io/api/image/2/level1.json" } }, - 'attribution' => 'Provided by Example Organization', - 'license' => 'http://www.example.org/license.html', - 'logo' => 'http://www.example.org/logos/institution1.jpg', - 'see_also' => 'http://www.example.org/library/catalog/book1.xml', - 'service' => { - '@context' => 'http://example.org/ns/jsonld/context.json', - '@id' => 'http://example.org/service/example', - 'profile' => 'http://example.org/docs/example-service.html' + "attribution" => "Provided by Example Organization", + "license" => "http://www.example.org/license.html", + "logo" => "http://www.example.org/logos/institution1.jpg", + "see_also" => "http://www.example.org/library/catalog/book1.xml", + "service" => { + "@context" => "http://example.org/ns/jsonld/context.json", + "@id" => "http://example.org/service/example", + "profile" => "http://example.org/docs/example-service.html" }, - 'related' => { - '@id' => 'http://www.example.org/videos/video-book1.mpg', - 'format' => 'video/mpeg' + "related" => { + "@id" => "http://www.example.org/videos/video-book1.mpg", + "format" => "video/mpeg" }, - 'within' => 'http://www.example.org/collections/books/', + "within" => "http://www.example.org/collections/books/" } end - describe '#initialize' do - it 'sets @type to sc:Manifest by default' do - expect(subject['@type']).to eq 'sc:Manifest' + describe "#initialize" do + it "sets @type to sc:Manifest by default" do + expect(subject["@type"]).to eq "sc:Manifest" end - it 'allows subclasses to override @type' do + it "allows subclasses to override @type" do sub = subclass_subject.new - expect(sub['@type']).to eq 'a:SubClass' + expect(sub["@type"]).to eq "a:SubClass" end end - describe '#required_keys' do - it 'accumulates' do - expect(subject.required_keys).to eq %w{ @type @id label } + describe "#required_keys" do + it "accumulates" do + expect(subject.required_keys).to eq %w[@type @id label] end end - describe '#validate' do - it 'raises an error if there is no @id' do - subject.label = 'Book 1' + describe "#validate" do + it "raises an error if there is no @id" do + subject.label = "Book 1" expect { subject.validate }.to raise_error IIIF::Presentation::MissingRequiredKeyError end - it 'raises an error if there is no label' do - subject['@id'] = 'http://www.example.org/iiif/book1/manifest' + it "raises an error if there is no label" do + subject["@id"] = "http://www.example.org/iiif/book1/manifest" expect { subject.validate }.to raise_error IIIF::Presentation::MissingRequiredKeyError end - it 'raises an error if there is no @type' do - subject.delete('@type') - subject.label = 'Book 1' - subject['@id'] = 'http://www.example.org/iiif/book1/manifest' + it "raises an error if there is no @type" do + subject.delete("@type") + subject.label = "Book 1" + subject["@id"] = "http://www.example.org/iiif/book1/manifest" expect { subject.validate }.to raise_error IIIF::Presentation::MissingRequiredKeyError end end describe "#{described_class}.define_methods_for_array_only_keys" do - it_behaves_like 'it has the appropriate methods for array-only keys' + it_behaves_like "it has the appropriate methods for array-only keys" end describe "#{described_class}.define_methods_for_string_only_keys" do - it_behaves_like 'it has the appropriate methods for string-only keys' + it_behaves_like "it has the appropriate methods for string-only keys" end describe "#{described_class}.define_methods_for_any_type_keys" do - it_behaves_like 'it has the appropriate methods for any-type keys' + it_behaves_like "it has the appropriate methods for any-type keys" end - end diff --git a/spec/unit/iiif/presentation/range_spec.rb b/spec/unit/iiif/presentation/range_spec.rb index 1cb257a..089127e 100644 --- a/spec/unit/iiif/presentation/range_spec.rb +++ b/spec/unit/iiif/presentation/range_spec.rb @@ -1,43 +1,39 @@ describe IIIF::Presentation::Range do - - let(:fixed_values) do + let(:fixed_values) do { - '@id' => 'http://www.example.org/iiif/book1/range/r1', - '@type' => 'sc:Range', - 'label' => 'Introduction', - 'ranges' => [ - 'http://www.example.org/iiif/book1/range/r1-1', - 'http://www.example.org/iiif/book1/range/r1-2' + "@id" => "http://www.example.org/iiif/book1/range/r1", + "@type" => "sc:Range", + "label" => "Introduction", + "ranges" => [ + "http://www.example.org/iiif/book1/range/r1-1", + "http://www.example.org/iiif/book1/range/r1-2" ], - 'canvases' => [ - 'http://www.example.org/iiif/book1/canvas/p1', - 'http://www.example.org/iiif/book1/canvas/p2', - 'http://www.example.org/iiif/book1/canvas/p3#xywh=0,0,750,300' + "canvases" => [ + "http://www.example.org/iiif/book1/canvas/p1", + "http://www.example.org/iiif/book1/canvas/p2", + "http://www.example.org/iiif/book1/canvas/p3#xywh=0,0,750,300" ] } end - describe '#initialize' do - it 'sets @type to sc:Range by default' do - expect(subject['@type']).to eq 'sc:Range' + describe "#initialize" do + it "sets @type to sc:Range by default" do + expect(subject["@type"]).to eq "sc:Range" end end describe "#{described_class}.define_methods_for_array_only_keys" do - it_behaves_like 'it has the appropriate methods for array-only keys' + it_behaves_like "it has the appropriate methods for array-only keys" end describe "#{described_class}.define_methods_for_string_only_keys" do - it_behaves_like 'it has the appropriate methods for string-only keys' + it_behaves_like "it has the appropriate methods for string-only keys" end describe "#{described_class}.define_methods_for_any_type_keys" do - it_behaves_like 'it has the appropriate methods for any-type keys' + it_behaves_like "it has the appropriate methods for any-type keys" end - describe '#validate' do + describe "#validate" do end - end - - diff --git a/spec/unit/iiif/presentation/resource_spec.rb b/spec/unit/iiif/presentation/resource_spec.rb index 3c46c42..35c74d0 100644 --- a/spec/unit/iiif/presentation/resource_spec.rb +++ b/spec/unit/iiif/presentation/resource_spec.rb @@ -1,16 +1,13 @@ describe IIIF::Presentation::Resource do - describe "#{described_class}.define_methods_for_abstract_resource_only_keys" do - it_behaves_like 'it has the appropriate methods for abstract_resource_only_keys' + it_behaves_like "it has the appropriate methods for abstract_resource_only_keys" end describe "#{described_class}.int_only_keys" do - it_behaves_like 'it has the appropriate methods for integer-only keys' + it_behaves_like "it has the appropriate methods for integer-only keys" end describe "#{described_class}.define_methods_for_string_only_keys" do - it_behaves_like 'it has the appropriate methods for string-only keys' + it_behaves_like "it has the appropriate methods for string-only keys" end - end - diff --git a/spec/unit/iiif/presentation/sequence_spec.rb b/spec/unit/iiif/presentation/sequence_spec.rb index 526f99d..bdd0086 100644 --- a/spec/unit/iiif/presentation/sequence_spec.rb +++ b/spec/unit/iiif/presentation/sequence_spec.rb @@ -1,110 +1,105 @@ describe IIIF::Presentation::Sequence do - let(:subclass_subject) do Class.new(IIIF::Presentation::Sequence) do - def initialize(hsh={}) - hsh = { '@type' => 'a:SubClass' } - super(hsh) + def initialize(_hsh = {}) + super({"@type" => "a:SubClass"}) end end end let(:fixed_values) do { - '@type' => 'sc:Sequence', - '@id' => 'http://example.com/prefix/sequence/456', - '@context' => IIIF::Presentation::CONTEXT, - 'label' => 'Book 1', - 'description' => 'A longer description of this example book. It should give some real information.', - 'thumbnail' => { - '@id' => 'http://www.example.org/images/book1-page1/full/80,100/0/default.jpg', - 'service'=> { - '@context' => 'http://iiif.io/api/image/2/context.json', - '@id' => 'http://www.example.org/images/book1-page1', - 'profile' => 'http://iiif.io/api/image/2/level1.json' + "@type" => "sc:Sequence", + "@id" => "http://example.com/prefix/sequence/456", + "@context" => IIIF::Presentation::CONTEXT, + "label" => "Book 1", + "description" => "A longer description of this example book. It should give some real information.", + "thumbnail" => { + "@id" => "http://www.example.org/images/book1-page1/full/80,100/0/default.jpg", + "service" => { + "@context" => "http://iiif.io/api/image/2/context.json", + "@id" => "http://www.example.org/images/book1-page1", + "profile" => "http://iiif.io/api/image/2/level1.json" } }, - 'attribution' => 'Provided by Example Organization', - 'license' => 'http://www.example.org/license.html', - 'logo' => 'http://www.example.org/logos/institution1.jpg', - 'see_also' => 'http://www.example.org/library/catalog/book1.xml', - 'service' => { - '@context' => 'http://example.org/ns/jsonld/context.json', - '@id' => 'http://example.org/service/example', - 'profile' => 'http://example.org/docs/example-service.html' + "attribution" => "Provided by Example Organization", + "license" => "http://www.example.org/license.html", + "logo" => "http://www.example.org/logos/institution1.jpg", + "see_also" => "http://www.example.org/library/catalog/book1.xml", + "service" => { + "@context" => "http://example.org/ns/jsonld/context.json", + "@id" => "http://example.org/service/example", + "profile" => "http://example.org/docs/example-service.html" }, - 'related' => { - '@id' => 'http://www.example.org/videos/video-book1.mpg', - 'format' => 'video/mpeg' + "related" => { + "@id" => "http://www.example.org/videos/video-book1.mpg", + "format" => "video/mpeg" }, - 'within' => 'http://www.example.org/collections/books/', + "within" => "http://www.example.org/collections/books/", # Sequence - 'metadata' => [{'label'=>'Author', 'value'=>'Anne Author'}], - 'canvases' => [{ - '@id' => 'http://www.example.org/iiif/book1/canvas/p1', - '@type' => 'sc:Canvas', - 'label' => 'p. 1', - 'height' => 1000, - 'width' => 750, - 'images'=> [] + "metadata" => [{"label" => "Author", "value" => "Anne Author"}], + "canvases" => [{ + "@id" => "http://www.example.org/iiif/book1/canvas/p1", + "@type" => "sc:Canvas", + "label" => "p. 1", + "height" => 1000, + "width" => 750, + "images" => [] }], - 'viewing_hint' => 'paged', - 'start_canvas' => 'http://www.example.org/iiif/book1/canvas/p2', - 'viewing_direction' => 'right-to-left', + "viewing_hint" => "paged", + "start_canvas" => "http://www.example.org/iiif/book1/canvas/p2", + "viewing_direction" => "right-to-left" } end - describe '#initialize' do - it 'sets @type to sc:Sequence by default' do - expect(subject['@type']).to eq 'sc:Sequence' + describe "#initialize" do + it "sets @type to sc:Sequence by default" do + expect(subject["@type"]).to eq "sc:Sequence" end - it 'allows subclasses to override @type' do + it "allows subclasses to override @type" do sub = subclass_subject.new - expect(sub['@type']).to eq 'a:SubClass' + expect(sub["@type"]).to eq "a:SubClass" end end - describe '#required_keys' do - it 'accumulates from the superclass' do - expect(subject.required_keys).to eq %w{ @type } + describe "#required_keys" do + it "accumulates from the superclass" do + expect(subject.required_keys).to eq %w[@type] end end - describe '#string_only_keys' do - it 'accumulates from the superclass' do - expect(subject.string_only_keys).to eq %w{ viewing_hint start_canvas viewing_direction } + describe "#string_only_keys" do + it "accumulates from the superclass" do + expect(subject.string_only_keys).to eq %w[viewing_hint start_canvas viewing_direction] end end - describe '#array_only_keys' do - it 'accumulates from the superclass' do - expect(subject.array_only_keys).to eq %w{ metadata canvases } + describe "#array_only_keys" do + it "accumulates from the superclass" do + expect(subject.array_only_keys).to eq %w[metadata canvases] end end describe "#{described_class}.define_methods_for_array_only_keys" do - it_behaves_like 'it has the appropriate methods for array-only keys' + it_behaves_like "it has the appropriate methods for array-only keys" end describe "#{described_class}.define_methods_for_string_only_keys" do - it_behaves_like 'it has the appropriate methods for string-only keys' + it_behaves_like "it has the appropriate methods for string-only keys" end describe "#{described_class}.define_methods_for_any_type_keys" do - it_behaves_like 'it has the appropriate methods for any-type keys' + it_behaves_like "it has the appropriate methods for any-type keys" end - describe '#validate' do - it 'raises an error if viewing_hint isn\'t an allowable value' do - subject['viewing_hint'] = 'foo' + describe "#validate" do + it "raises an error if viewing_hint isn't an allowable value" do + subject["viewing_hint"] = "foo" expect { subject.validate }.to raise_error IIIF::Presentation::IllegalValueError end - it 'raises an error if viewing_directon isn\'t an allowable value' do - subject['viewing_direction'] = 'foo-to-bar' + it "raises an error if viewing_directon isn't an allowable value" do + subject["viewing_direction"] = "foo-to-bar" expect { subject.validate }.to raise_error IIIF::Presentation::IllegalValueError end end - - end - diff --git a/spec/unit/iiif/presentation/shared_examples/abstract_resource_only_keys.rb b/spec/unit/iiif/presentation/shared_examples/abstract_resource_only_keys.rb index 17da225..cfacb31 100644 --- a/spec/unit/iiif/presentation/shared_examples/abstract_resource_only_keys.rb +++ b/spec/unit/iiif/presentation/shared_examples/abstract_resource_only_keys.rb @@ -1,9 +1,5 @@ -require 'set' - -shared_examples 'it has the appropriate methods for abstract_resource_only_keys' do - +shared_examples "it has the appropriate methods for abstract_resource_only_keys" do described_class.new.abstract_resource_only_keys.each do |entry| - describe "#{entry[:key]}=" do it "sets #{entry[:key]}" do @ex = entry[:type].new @@ -19,11 +15,11 @@ end it "raises an exception when attempting to set it to something other than an #{entry[:type]}" do e = IIIF::Presentation::IllegalValueError - expect { subject.send("#{entry[:key]}=", 'Foo') }.to raise_error e + expect { subject.send("#{entry[:key]}=", "Foo") }.to raise_error e end end - describe "#{entry[:key]}" do + describe entry[:key].to_s do it "gets #{entry[:key]}" do @ex = entry[:type].new subject[entry[:key]] = @ex @@ -33,11 +29,9 @@ it "is aliased as ##{entry[:key].camelize(:lower)}" do @ex = entry[:type].new subject[entry[:key]] = @ex - expect(subject.send("#{entry[:key].camelize(:lower)}")).to eq @ex + expect(subject.send(entry[:key].camelize(:lower).to_s)).to eq @ex end end end - end - end diff --git a/spec/unit/iiif/presentation/shared_examples/any_type_keys.rb b/spec/unit/iiif/presentation/shared_examples/any_type_keys.rb index e218632..98872ee 100644 --- a/spec/unit/iiif/presentation/shared_examples/any_type_keys.rb +++ b/spec/unit/iiif/presentation/shared_examples/any_type_keys.rb @@ -1,7 +1,4 @@ -require 'set' - -shared_examples 'it has the appropriate methods for any-type keys' do - +shared_examples "it has the appropriate methods for any-type keys" do described_class.new.any_type_keys.each do |prop| describe "##{prop}=" do it "sets self['#{prop}']" do @@ -18,16 +15,15 @@ describe "##{prop}" do it "gets self[#{prop}]" do - subject.send("[]=", prop, fixed_values[prop]) - expect(subject.send("#{prop}")).to eq fixed_values[prop] + subject.send(:[]=, prop, fixed_values[prop]) + expect(subject.send(prop.to_s)).to eq fixed_values[prop] end if prop.camelize(:lower) != prop it "is aliased as ##{prop.camelize(:lower)}" do - subject.send("[]=", prop, fixed_values[prop]) - expect(subject.send("#{prop.camelize(:lower)}")).to eq fixed_values[prop] + subject.send(:[]=, prop, fixed_values[prop]) + expect(subject.send(prop.camelize(:lower).to_s)).to eq fixed_values[prop] end end end end - end diff --git a/spec/unit/iiif/presentation/shared_examples/array_only_keys.rb b/spec/unit/iiif/presentation/shared_examples/array_only_keys.rb index 49479de..ee03372 100644 --- a/spec/unit/iiif/presentation/shared_examples/array_only_keys.rb +++ b/spec/unit/iiif/presentation/shared_examples/array_only_keys.rb @@ -1,44 +1,36 @@ -require 'set' - -shared_examples 'it has the appropriate methods for array-only keys' do - +shared_examples "it has the appropriate methods for array-only keys" do described_class.new.array_only_keys.each do |prop| - describe "#{prop}=" do it "sets #{prop}" do - ex = [{'label' => 'XYZ'}] + ex = [{"label" => "XYZ"}] subject.send("#{prop}=", ex) expect(subject[prop]).to eq ex end if prop.camelize(:lower) != prop it "is aliased as ##{prop.camelize(:lower)}=" do - ex = [{'label' => 'XYZ'}] + ex = [{"label" => "XYZ"}] subject.send("#{prop.camelize(:lower)}=", ex) expect(subject[prop]).to eq ex end end - it 'raises an exception when attempting to set it to something other than an Array' do - expect { subject.send("#{prop}=", 'Foo') }.to raise_error IIIF::Presentation::IllegalValueError + it "raises an exception when attempting to set it to something other than an Array" do + expect { subject.send("#{prop}=", "Foo") }.to raise_error IIIF::Presentation::IllegalValueError end end - describe "#{prop}" do + describe prop.to_s do it "gets #{prop}" do - ex = [{'label' => 'XYZ'}] + ex = [{"label" => "XYZ"}] subject[prop] = ex expect(subject.send(prop)).to eq ex end if prop.camelize(:lower) != prop it "is aliased as ##{prop.camelize(:lower)}" do - ex = [{'label' => 'XYZ'}] + ex = [{"label" => "XYZ"}] subject[prop] = ex - expect(subject.send("#{prop.camelize(:lower)}")).to eq ex + expect(subject.send(prop.camelize(:lower).to_s)).to eq ex end end end - end - end - - diff --git a/spec/unit/iiif/presentation/shared_examples/int_only_keys.rb b/spec/unit/iiif/presentation/shared_examples/int_only_keys.rb index e4793ca..a16ea9f 100644 --- a/spec/unit/iiif/presentation/shared_examples/int_only_keys.rb +++ b/spec/unit/iiif/presentation/shared_examples/int_only_keys.rb @@ -1,9 +1,5 @@ -require 'set' - -shared_examples 'it has the appropriate methods for integer-only keys' do - +shared_examples "it has the appropriate methods for integer-only keys" do described_class.new.int_only_keys.each do |prop| - describe "#{prop}=" do before(:all) do @ex = 7200 @@ -18,15 +14,15 @@ expect(subject[prop]).to eq @ex end end - it 'raises an exception when attempting to set it to something other than an Integer' do - expect { subject.send("#{prop}=", 'Foo') }.to raise_error IIIF::Presentation::IllegalValueError + it "raises an exception when attempting to set it to something other than an Integer" do + expect { subject.send("#{prop}=", "Foo") }.to raise_error IIIF::Presentation::IllegalValueError end - it 'raises an exception when attempting to set it to a negative number' do + it "raises an exception when attempting to set it to a negative number" do expect { subject.send("#{prop}=", -1) }.to raise_error IIIF::Presentation::IllegalValueError end end - describe "#{prop}" do + describe prop.to_s do before(:all) do @ex = 7200 end @@ -37,13 +33,9 @@ if prop.camelize(:lower) != prop it "is aliased as ##{prop.camelize(:lower)}" do subject[prop] = @ex - expect(subject.send("#{prop.camelize(:lower)}")).to eq @ex + expect(subject.send(prop.camelize(:lower).to_s)).to eq @ex end end end - end - end - - diff --git a/spec/unit/iiif/presentation/shared_examples/string_only_keys.rb b/spec/unit/iiif/presentation/shared_examples/string_only_keys.rb index e5128d1..d7a4c3f 100644 --- a/spec/unit/iiif/presentation/shared_examples/string_only_keys.rb +++ b/spec/unit/iiif/presentation/shared_examples/string_only_keys.rb @@ -1,29 +1,22 @@ -require 'set' - -shared_examples 'it has the appropriate methods for string-only keys' do - +shared_examples "it has the appropriate methods for string-only keys" do described_class.new.string_only_keys.each do |prop| - describe "#{prop}=" do it "sets #{prop}" do - ex = 'foo' + ex = "foo" subject.send("#{prop}=", ex) expect(subject[prop]).to eq ex end - it 'raises an exception when attempting to set it to something other than a String' do - expect { subject.send("#{prop}=", ['Foo']) }.to raise_error IIIF::Presentation::IllegalValueError + it "raises an exception when attempting to set it to something other than a String" do + expect { subject.send("#{prop}=", ["Foo"]) }.to raise_error IIIF::Presentation::IllegalValueError end end - describe "#{prop}" do + describe prop.to_s do it "gets #{prop}" do - ex = 'bar' + ex = "bar" subject[prop] = ex expect(subject.send(prop)).to eq ex end end - end - end - diff --git a/spec/unit/iiif/service_spec.rb b/spec/unit/iiif/service_spec.rb index be7d1ca..381535f 100644 --- a/spec/unit/iiif/service_spec.rb +++ b/spec/unit/iiif/service_spec.rb @@ -1,28 +1,23 @@ describe IIIF::Service do - - describe 'self#get_descendant_class_by_jld_type' do - before do - class DummyClass < IIIF::Service - TYPE = "sc:Collection" + describe "self#get_descendant_class_by_jld_type" do + let(:dummy_class) do + Class.new(IIIF::Service) do + const_set(:TYPE, "sc:Collection") def self.singleton_class? true end end end - after do - Object.send(:remove_const, :DummyClass) - end - it 'gets the right class' do - klass = described_class.get_descendant_class_by_jld_type('sc:Canvas') + it "gets the right class" do + klass = described_class.get_descendant_class_by_jld_type("sc:Canvas") expect(klass).to be IIIF::Presentation::Canvas end context "when there are singleton classes which are returned" do it "gets the right class" do - allow(IIIF::Service).to receive(:descendants).and_return([DummyClass, IIIF::Presentation::Collection]) - klass = described_class.get_descendant_class_by_jld_type('sc:Collection') + allow(IIIF::Service).to receive(:descendants).and_return([dummy_class, IIIF::Presentation::Collection]) + klass = described_class.get_descendant_class_by_jld_type("sc:Collection") expect(klass).to be IIIF::Presentation::Collection end end end - end diff --git a/spec/unit/iiif/v3/abstract_resource_define_methods_for_spec.rb b/spec/unit/iiif/v3/abstract_resource_define_methods_for_spec.rb index cad3e7b..9de83d1 100644 --- a/spec/unit/iiif/v3/abstract_resource_define_methods_for_spec.rb +++ b/spec/unit/iiif/v3/abstract_resource_define_methods_for_spec.rb @@ -1,78 +1,80 @@ class AbstractResourceSubClass < IIIF::V3::AbstractResource - TYPE = 'Ignore' + TYPE = "Ignore" # need a property here for type of key not already initialized in AbstractResource def array_only_keys - super + %w{ array my_array } + super + %w[array my_array] end + def hash_only_keys - super + %w{ hash my_hash } + super + %w[hash my_hash] end + def int_only_keys - super + %w{ int my_int } + super + %w[int my_int] end + def numeric_only_keys - super + %w{ num my_num } + super + %w[num my_num] end + def uri_only_keys - super + %w{ uri my_uri } + super + %w[uri my_uri] end - def initialize(hsh={}) - hsh = { 'type' => 'a:SubClass' } - super(hsh) + def initialize(_hsh = {}) + super({"type" => "a:SubClass"}) end end describe AbstractResourceSubClass do - describe "*define_methods_for_any_type_keys" do # shared_example expects fixed_values; these are roughly based on Stanford purl code # (see https://github.com/sul-dlss/purl/blob/master/app/models/iiif3_presentation_manifest.rb) let(:fixed_values) do { - 'label' => 'foo', - 'description' => 'bar', - 'thumbnail' => IIIF::V3::Presentation::ImageResource.new( - 'type' => 'Image', - 'id' => "http://example.org/full/!400,400/0/default.jpg", - 'format' => 'image/jpeg' - ), - 'attribution' => ['foo'], - 'logo' => { - 'id' => 'https://example.org/default.jpg', - 'service' => IIIF::V3::Presentation::Service.new( - '@context' => 'http://iiif.io/api/image/2/context.json', - '@id' => 'http://example.org/1', - 'id' => 'http://example.org/1', - 'profile' => 'http://example.org/whatever' + "label" => "foo", + "description" => "bar", + "thumbnail" => IIIF::V3::Presentation::ImageResource.new( + "type" => "Image", + "id" => "http://example.org/full/!400,400/0/default.jpg", + "format" => "image/jpeg" + ), + "attribution" => ["foo"], + "logo" => { + "id" => "https://example.org/default.jpg", + "service" => IIIF::V3::Presentation::Service.new( + "@context" => "http://iiif.io/api/image/2/context.json", + "@id" => "http://example.org/1", + "id" => "http://example.org/1", + "profile" => "http://example.org/whatever" ) }, - 'see_also' => { - 'id' => 'http://example.org/whatever', - 'format' => 'application/mods+xml' + "see_also" => { + "id" => "http://example.org/whatever", + "format" => "application/mods+xml" }, - 'related' => ['no', 'idea'], - 'within' => {'foo' => 'bar'} + "related" => ["no", "idea"], + "within" => {"foo" => "bar"} } end - it_behaves_like 'it has the appropriate methods for any-type keys v3' + it_behaves_like "it has the appropriate methods for any-type keys v3" end describe "*define_methods_for_array_only_keys" do - it_behaves_like 'it has the appropriate methods for array-only keys v3' + it_behaves_like "it has the appropriate methods for array-only keys v3" end describe "*define_methods_for_hash_only_keys" do - it_behaves_like 'it has the appropriate methods for hash-only keys v3' + it_behaves_like "it has the appropriate methods for hash-only keys v3" end describe "*define_methods_for_int_only_keys" do - it_behaves_like 'it has the appropriate methods for integer-only keys v3' + it_behaves_like "it has the appropriate methods for integer-only keys v3" end describe "*define_methods_for_numeric_only_keys" do - it_behaves_like 'it has the appropriate methods for numeric-only keys v3' + it_behaves_like "it has the appropriate methods for numeric-only keys v3" end describe "*define_methods_for_string_only_keys" do - it_behaves_like 'it has the appropriate methods for string-only keys v3' + it_behaves_like "it has the appropriate methods for string-only keys v3" end describe "*define_methods_for_uri_only_keys" do - it_behaves_like 'it has the appropriate methods for uri-only keys v3' + it_behaves_like "it has the appropriate methods for uri-only keys v3" end end diff --git a/spec/unit/iiif/v3/abstract_resource_spec.rb b/spec/unit/iiif/v3/abstract_resource_spec.rb index 701a39b..ccb9595 100644 --- a/spec/unit/iiif/v3/abstract_resource_spec.rb +++ b/spec/unit/iiif/v3/abstract_resource_spec.rb @@ -1,285 +1,278 @@ -require 'active_support/inflector' -require 'json' -require_relative '../../../../lib/iiif/hash_behaviours' +require "active_support/inflector" +require "json" +require_relative "../../../../lib/iiif/hash_behaviours" describe IIIF::V3::AbstractResource do - - let(:fixtures_dir) { File.join(File.dirname(__FILE__), '../../../fixtures') } - let(:manifest_from_spec_path) { File.join(fixtures_dir, 'v3/manifests/complete_from_spec.json') } + let(:fixtures_dir) { File.join(File.dirname(__FILE__), "../../../fixtures") } + let(:manifest_from_spec_path) { File.join(fixtures_dir, "v3/manifests/complete_from_spec.json") } let(:abstract_resource_subclass) do Class.new(IIIF::V3::AbstractResource) do include IIIF::HashBehaviours - def initialize(hsh={}) - hsh['type'] = 'a:SubClass' unless hsh.has_key?('type') - super(hsh) + def initialize(hsh = {}) + hsh["type"] = "a:SubClass" unless hsh.has_key?("type") + super end def required_keys - super + %w{ id } + super + %w[id] end def prohibited_keys - super + %w{ verboten } + super + %w[verboten] end def legal_viewing_hint_values - %w{ viewing_hint1 viewing_hint2 } + %w[viewing_hint1 viewing_hint2] end end end subject do instance = abstract_resource_subclass.new - instance['id'] = 'http://example.com/prefix/manifest/123' + instance["id"] = "http://example.com/prefix/manifest/123" instance end - describe '#required_keys' do - it 'accumulate' do - expect(subject.required_keys).to eq %w{ type id } + describe "#required_keys" do + it "accumulate" do + expect(subject.required_keys).to eq %w[type id] end end - describe '#initialize' do - it 'raises an error if you try to instantiate AbstractResource' do + describe "#initialize" do + it "raises an error if you try to instantiate AbstractResource" do expect { IIIF::V3::AbstractResource.new }.to raise_error(RuntimeError) end - it 'sets type' do - expect(subject['type']).to eq 'a:SubClass' + it "sets type" do + expect(subject["type"]).to eq "a:SubClass" end - it 'can take any old hash' do + it "can take any old hash" do hsh = JSON.parse(IO.read(manifest_from_spec_path)) new_instance = abstract_resource_subclass.new(hsh) - expect(new_instance['label']['en']).to include 'Book 1' + expect(new_instance["label"]["en"]).to include "Book 1" end end - describe '#validate' do - it 'raises MissingRequiredKeyError if required key is missing' do + describe "#validate" do + it "raises MissingRequiredKeyError if required key is missing" do subject.required_keys.each { |k| subject.delete(k) } expect { subject.validate }.to raise_error IIIF::V3::Presentation::MissingRequiredKeyError end - it 'raises ProhibitedKeyError if prohibited key is present' do - subject['verboten'] = 666 + it "raises ProhibitedKeyError if prohibited key is present" do + subject["verboten"] = 666 exp_err_msg = "verboten is a prohibited key in #{subject.class}" expect { subject.validate }.to raise_error(IIIF::V3::Presentation::ProhibitedKeyError, exp_err_msg) end - it 'raises IllegalValueError for bad viewing_direction' do - subject['viewing_direction'] = 'foo' + it "raises IllegalValueError for bad viewing_direction" do + subject["viewing_direction"] = "foo" exp_err_msg = "viewingDirection must be one of #{subject.legal_viewing_direction_values}" expect { subject.validate }.to raise_error(IIIF::V3::Presentation::IllegalValueError, exp_err_msg) end - describe 'viewing_hint' do - it 'can be a uri' do - subject['viewing_hint'] = 'https://example.org/viewiing_hint' + describe "viewing_hint" do + it "can be a uri" do + subject["viewing_hint"] = "https://example.org/viewiing_hint" expect { subject.validate }.not_to raise_error end - it 'can be a member of legal_viewing_hint_values' do - subject['viewing_hint'] = subject.legal_viewing_hint_values.first + it "can be a member of legal_viewing_hint_values" do + subject["viewing_hint"] = subject.legal_viewing_hint_values.first expect { subject.validate }.not_to raise_error end - it 'raises IllegalValueError for bad viewing_hint' do - subject['viewing_hint'] = 'foo' + it "raises IllegalValueError for bad viewing_hint" do + subject["viewing_hint"] = "foo" exp_err_msg = "viewingHint for #{subject.class} must be one or more of #{subject.legal_viewing_hint_values} or a URI" expect { subject.validate }.to raise_error(IIIF::V3::Presentation::IllegalValueError, exp_err_msg) end - it 'can have multiple values' do - subject['viewing_hint'] = [subject.legal_viewing_hint_values.first, subject.legal_viewing_hint_values.last] + it "can have multiple values" do + subject["viewing_hint"] = [subject.legal_viewing_hint_values.first, subject.legal_viewing_hint_values.last] expect { subject.validate }.not_to raise_error end end - describe 'metadata' do - it 'raises IllegalValueError for entry that is not a Hash' do - subject['metadata'] = ['error'] + describe "metadata" do + it "raises IllegalValueError for entry that is not a Hash" do + subject["metadata"] = ["error"] exp_err_msg = "metadata must be an Array with Hash members" expect { subject.validate }.to raise_error(IIIF::V3::Presentation::IllegalValueError, exp_err_msg) end it 'does not raise error for entry that contains exactly "label" and "value"' do - subject['metadata'] = [{ 'label' => 'bar', 'value' => 'foo' }] + subject["metadata"] = [{"label" => "bar", "value" => "foo"}] expect { subject.validate }.not_to raise_error end it 'raises IllegalValueError for entry that does not contain exactly "label" and "value"' do - subject['metadata'] = [{ 'label' => 'bar', 'bar' => 'foo' }] + subject["metadata"] = [{"label" => "bar", "bar" => "foo"}] exp_err_msg = "metadata members must be a Hash of keys 'label' and 'value'" expect { subject.validate }.to raise_error(IIIF::V3::Presentation::IllegalValueError, exp_err_msg) end end - describe 'thumbnail' do - let (:exp_basic_err_msg) { "thumbnail must be an Array with Hash or ImageResource members" } - let (:exp_keys_msg) { 'thumbnail members must include keys "id" and "type"' } - it 'raises IllegalValueError for entry that is not a Hash or ImageResource object' do - subject['thumbnail'] = ['error'] + describe "thumbnail" do + let(:exp_basic_err_msg) { "thumbnail must be an Array with Hash or ImageResource members" } + let(:exp_keys_msg) { 'thumbnail members must include keys "id" and "type"' } + it "raises IllegalValueError for entry that is not a Hash or ImageResource object" do + subject["thumbnail"] = ["error"] expect { subject.validate }.to raise_error(IIIF::V3::Presentation::IllegalValueError, exp_basic_err_msg) end it 'does not raise error for entry Hash with "id" and "type"' do - subject['thumbnail'] = [{ 'id' => 'bar', 'type' => 'foo', 'random' => 'xxx' }] + subject["thumbnail"] = [{"id" => "bar", "type" => "foo", "random" => "xxx"}] expect { subject.validate }.not_to raise_error end it 'raises IllegalValueError for entry Hash that does not contain "id" and "type"' do - subject['thumbnail'] = [{ 'id' => 'bar' }] + subject["thumbnail"] = [{"id" => "bar"}] expect { subject.validate }.to raise_error(IIIF::V3::Presentation::IllegalValueError, exp_keys_msg) end it 'does not raise error for entry ImageResource with "id"' do - subject['thumbnail'] = [IIIF::V3::Presentation::ImageResource.new({ 'id' => 'bar', 'label' => 'xxx' })] + subject["thumbnail"] = [IIIF::V3::Presentation::ImageResource.new({"id" => "bar", "label" => "xxx"})] expect { subject.validate }.not_to raise_error end - it 'raises IllegalValueError for entry ImageResource without id' do - subject['thumbnail'] = [IIIF::V3::Presentation::ImageResource.new] + it "raises IllegalValueError for entry ImageResource without id" do + subject["thumbnail"] = [IIIF::V3::Presentation::ImageResource.new] expect { subject.validate }.to raise_error(IIIF::V3::Presentation::IllegalValueError, exp_keys_msg) end end - describe 'nav_date' do - it 'does not raise error for value of form YYYY-MM-DDThh:mm:ssZ' do - subject['nav_date'] = '1991-01-02T13:04:27Z' + describe "nav_date" do + it "does not raise error for value of form YYYY-MM-DDThh:mm:ssZ" do + subject["nav_date"] = "1991-01-02T13:04:27Z" expect { subject.validate }.not_to raise_error end - it 'raises IllegalValueError for value not of form YYYY-MM-DDThh:mm:ssZ' do - subject['nav_date'] = '1991-01-02T13:04:27+0500' - exp_err_msg = 'nav_date must be of form YYYY-MM-DDThh:mm:ssZ' + it "raises IllegalValueError for value not of form YYYY-MM-DDThh:mm:ssZ" do + subject["nav_date"] = "1991-01-02T13:04:27+0500" + exp_err_msg = "nav_date must be of form YYYY-MM-DDThh:mm:ssZ" expect { subject.validate }.to raise_error(IIIF::V3::Presentation::IllegalValueError, exp_err_msg) end end - describe 'rights' do - it 'raises IllegalValueError for entry that is not a string' do - subject['rights'] = ['error'] + describe "rights" do + it "raises IllegalValueError for entry that is not a string" do + subject["rights"] = ["error"] expect { subject.validate }.to raise_error(IIIF::V3::Presentation::IllegalValueError) end - it 'does not raise error for entry that is string' do - subject['rights'] = 'http://example.org/rights' + it "does not raise error for entry that is string" do + subject["rights"] = "http://example.org/rights" expect { subject.validate }.not_to raise_error end end - describe 'rendering' do - it 'raises IllegalValueError for entry that is not a Hash' do - subject['rendering'] = ['error'] + describe "rendering" do + it "raises IllegalValueError for entry that is not a Hash" do + subject["rendering"] = ["error"] exp_err_msg = "rendering must be an Array with Hash members" expect { subject.validate }.to raise_error(IIIF::V3::Presentation::IllegalValueError, exp_err_msg) end it 'does not raise error for entry with "label" and "format"' do - subject['rendering'] = [{ 'label' => 'bar', 'format' => 'foo', 'random' => 'xxx' }] + subject["rendering"] = [{"label" => "bar", "format" => "foo", "random" => "xxx"}] expect { subject.validate }.not_to raise_error end it 'raises IllegalValueError for entry that does not contain "label" and "format"' do - subject['rendering'] = [{ 'label' => 'bar' }] + subject["rendering"] = [{"label" => "bar"}] exp_err_msg = 'rendering members must be a Hash including keys "label" and "format"' expect { subject.validate }.to raise_error(IIIF::V3::Presentation::IllegalValueError, exp_err_msg) end end - describe 'startCanvas' do - it 'raises IllegalValueError for entry that is not URI' do - subject.startCanvas = 'foo' + describe "startCanvas" do + it "raises IllegalValueError for entry that is not URI" do + subject.startCanvas = "foo" exp_err_msg = "startCanvas value must be a String containing a URI for #{subject.class}" expect { subject.validate }.to raise_error(IIIF::V3::Presentation::IllegalValueError, exp_err_msg) end end end - describe 'A nested object (e.g. self[\'metadata\'])' do - it 'returns [] if not set' do + describe "A nested object (e.g. self['metadata'])" do + it "returns [] if not set" do expect(subject.metadata).to eq([]) end - it 'is not in #to_ordered_hash at all if we access it but do not append to it' do + it "is not in #to_ordered_hash at all if we access it but do not append to it" do subject.metadata # touch it expect(subject.metadata).to eq([]) - expect(subject.to_ordered_hash.has_key?('metadata')).to be_falsey + expect(subject.to_ordered_hash.has_key?("metadata")).to be_falsey end - it 'gets structured as we\'d expect' do + it "gets structured as we'd expect" do subject.metadata << { - 'label' => 'Author', - 'value' => 'Anne Author' + "label" => "Author", + "value" => "Anne Author" } subject.metadata << { - 'label' => 'Published', - 'value' => [ - {'@value'=> 'Paris, circa 1400', '@language'=>'en'}, - {'@value'=> 'Paris, environ 14eme siecle', '@language'=>'fr'} + "label" => "Published", + "value" => [ + {"@value" => "Paris, circa 1400", "@language" => "en"}, + {"@value" => "Paris, environ 14eme siecle", "@language" => "fr"} ] } - expect(subject.metadata[0]['label']).to eq('Author') - expect(subject.metadata[1]['value'].length).to eq(2) - expect(subject.metadata[1]['value'].select { |e| e['@language'] == 'fr'}.last['@value']).to eq('Paris, environ 14eme siecle') + expect(subject.metadata[0]["label"]).to eq("Author") + expect(subject.metadata[1]["value"].length).to eq(2) + expect(subject.metadata[1]["value"].reverse.find { |e| e["@language"] == "fr" }["@value"]).to eq("Paris, environ 14eme siecle") end - it 'roundtrips' do + it "roundtrips" do subject.metadata << { - 'label' => 'Author', - 'value' => 'Anne Author' + "label" => "Author", + "value" => "Anne Author" } subject.metadata << { - 'label' => 'Published', - 'value' => [ - {'@value'=> 'Paris, circa 1400', '@language'=>'en'}, - {'@value'=> 'Paris, environ 14eme siecle', '@language'=>'fr'} + "label" => "Published", + "value" => [ + {"@value" => "Paris, circa 1400", "@language" => "en"}, + {"@value" => "Paris, environ 14eme siecle", "@language" => "fr"} ] } - File.open('/tmp/osullivan-spec.json','w') do |f| - f.write(subject.to_json) - end - parsed = subject.class.parse('/tmp/osullivan-spec.json') - expect(parsed['metadata'][0]['label']).to eq('Author') - expect(parsed['metadata'][1]['value'].length).to eq(2) - expect(parsed['metadata'][1]['value'].select { |e| e['@language'] == 'fr'}.last['@value']).to eq('Paris, environ 14eme siecle') - File.delete('/tmp/osullivan-spec.json') + File.write("/tmp/osullivan-spec.json", subject.to_json) + parsed = subject.class.parse("/tmp/osullivan-spec.json") + expect(parsed["metadata"][0]["label"]).to eq("Author") + expect(parsed["metadata"][1]["value"].length).to eq(2) + expect(parsed["metadata"][1]["value"].reverse.find { |e| e["@language"] == "fr" }["@value"]).to eq("Paris, environ 14eme siecle") + File.delete("/tmp/osullivan-spec.json") end end - describe '#to_ordered_hash' do - describe 'adds the @context' do - before(:each) { subject.delete('@context') } - it 'by default' do - expect(subject.has_key?('@context')).to be_falsey - expect(subject.to_ordered_hash.has_key?('@context')).to be_truthy - end - it 'unless you say not to' do - expect(subject.has_key?('@context')).to be_falsey - expect(subject.to_ordered_hash(include_context: false).has_key?('@context')).to be_falsey - end - it 'or it\'s already there' do - different_ctxt = 'http://example.org/context' - subject['@context'] = different_ctxt + describe "#to_ordered_hash" do + describe "adds the @context" do + before(:each) { subject.delete("@context") } + it "by default" do + expect(subject.has_key?("@context")).to be_falsey + expect(subject.to_ordered_hash.has_key?("@context")).to be_truthy + end + it "unless you say not to" do + expect(subject.has_key?("@context")).to be_falsey + expect(subject.to_ordered_hash(include_context: false).has_key?("@context")).to be_falsey + end + it "or it's already there" do + different_ctxt = "http://example.org/context" + subject["@context"] = different_ctxt oh = subject.to_ordered_hash - expect(oh['@context']).to eq different_ctxt + expect(oh["@context"]).to eq different_ctxt end end - describe 'runs the validations' do + describe "runs the validations" do let(:error) { IIIF::V3::Presentation::MissingRequiredKeyError } - before(:each) { subject.delete('id') } - it 'raises exceptions' do + before(:each) { subject.delete("id") } + it "raises exceptions" do expect { subject.to_ordered_hash }.to raise_error error end - it 'unless you tell it not to' do + it "unless you tell it not to" do expect { subject.to_ordered_hash(force: true) }.to_not raise_error end end end - describe '*get_descendant_class_by_jld_type' do - before do - class DummyClass < IIIF::V3::AbstractResource - TYPE = "Collection" + describe "*get_descendant_class_by_jld_type" do + let(:dummy_class) do + Class.new(IIIF::V3::AbstractResource) do + const_set(:TYPE, "Collection") def self.singleton_class? true end end end - after do - Object.send(:remove_const, :DummyClass) - end - it 'gets the right class' do - klass = described_class.get_descendant_class_by_jld_type('Canvas') + it "gets the right class" do + klass = described_class.get_descendant_class_by_jld_type("Canvas") expect(klass).to eq IIIF::V3::Presentation::Canvas end context "when there are singleton classes which are returned" do it "gets the right class" do - allow(IIIF::V3::AbstractResource).to receive(:descendants).and_return([DummyClass, IIIF::V3::Presentation::Collection]) - klass = described_class.get_descendant_class_by_jld_type('Collection') + allow(IIIF::V3::AbstractResource).to receive(:descendants).and_return([dummy_class, IIIF::V3::Presentation::Collection]) + klass = described_class.get_descendant_class_by_jld_type("Collection") expect(klass).to eq IIIF::V3::Presentation::Collection end end end - end diff --git a/spec/unit/iiif/v3/presentation/annotation_collection_spec.rb b/spec/unit/iiif/v3/presentation/annotation_collection_spec.rb index 0d796cd..5ea22e9 100644 --- a/spec/unit/iiif/v3/presentation/annotation_collection_spec.rb +++ b/spec/unit/iiif/v3/presentation/annotation_collection_spec.rb @@ -1,36 +1,33 @@ describe IIIF::V3::Presentation::AnnotationCollection do - let(:fixed_values) do { - '@context' => [ - 'http://iiif.io/api/presentation/3/context.json', - 'http://www.w3.org/ns/anno.jsonld' + "@context" => [ + "http://iiif.io/api/presentation/3/context.json", + "http://www.w3.org/ns/anno.jsonld" ], - 'id' => 'http://www.example.org/iiif/book1/annoColl/transcription', - 'type' => 'AnnotationCollection', - 'label' => 'Diplomatic Transcription', - 'first' => 'http://www.example.org/iiif/book1/list/l1', - 'last' => 'http://www.example.org/iiif/book1/list/l4', + "id" => "http://www.example.org/iiif/book1/annoColl/transcription", + "type" => "AnnotationCollection", + "label" => "Diplomatic Transcription", + "first" => "http://www.example.org/iiif/book1/list/l1", + "last" => "http://www.example.org/iiif/book1/list/l4" } end - - describe '#initialize' do - it 'sets type' do - expect(subject['type']).to eq 'AnnotationCollection' + describe "#initialize" do + it "sets type" do + expect(subject["type"]).to eq "AnnotationCollection" end end describe "#{described_class}.define_methods_for_string_only_keys" do - it_behaves_like 'it has the appropriate methods for string-only keys v3' + it_behaves_like "it has the appropriate methods for string-only keys v3" end describe "#{described_class}.define_methods_for_array_only_keys" do - it_behaves_like 'it has the appropriate methods for array-only keys v3' + it_behaves_like "it has the appropriate methods for array-only keys v3" end describe "#{described_class}.define_methods_for_any_type_keys" do - it_behaves_like 'it has the appropriate methods for any-type keys v3' + it_behaves_like "it has the appropriate methods for any-type keys v3" end - end diff --git a/spec/unit/iiif/v3/presentation/annotation_page_spec.rb b/spec/unit/iiif/v3/presentation/annotation_page_spec.rb index 5df72df..52eaa71 100644 --- a/spec/unit/iiif/v3/presentation/annotation_page_spec.rb +++ b/spec/unit/iiif/v3/presentation/annotation_page_spec.rb @@ -1,129 +1,131 @@ describe IIIF::V3::Presentation::AnnotationPage do - - describe '#required_keys' do - it 'id' do - expect(subject.required_keys).to include('id') + describe "#required_keys" do + it "id" do + expect(subject.required_keys).to include("id") end end - describe '#prohibited_keys' do - it 'contains the expected key names' do + describe "#prohibited_keys" do + it "contains the expected key names" do keys = described_class::CONTENT_RESOURCE_PROPERTIES + - %w{ - first - last - total - nav_date - viewing_direction - start_canvas - content_annotations - } - expect(subject.prohibited_keys).to include(*keys) - end + %w[ + first + last + total + nav_date + viewing_direction + start_canvas + content_annotations + ] + expect(subject.prohibited_keys).to include(*keys) + end end - describe '#uri_only_keys' do - it 'id' do - expect(subject.uri_only_keys).to include('id') + describe "#uri_only_keys" do + it "id" do + expect(subject.uri_only_keys).to include("id") end end - describe '#array_only_keys' do - it 'items' do - expect(subject.array_only_keys).to include('items') + describe "#array_only_keys" do + it "items" do + expect(subject.array_only_keys).to include("items") end end - describe '#legal_viewing_hint_values' do - it 'contains none' do - expect(subject.legal_viewing_hint_values).to contain_exactly('none') + describe "#legal_viewing_hint_values" do + it "contains none" do + expect(subject.legal_viewing_hint_values).to contain_exactly("none") end end - describe '#initialize' do - it 'sets type to AnnotationPage by default' do - expect(subject['type']).to eq 'AnnotationPage' + describe "#initialize" do + it "sets type to AnnotationPage by default" do + expect(subject["type"]).to eq "AnnotationPage" end - it 'allows subclasses to override type' do + it "allows subclasses to override type" do subclass = Class.new(described_class) do - def initialize(hsh={}) - hsh = { 'type' => 'a:SubClass' } - super(hsh) + def initialize(_hsh = {}) + super({"type" => "a:SubClass"}) end end sub = subclass.new - expect(sub['type']).to eq 'a:SubClass' + expect(sub["type"]).to eq "a:SubClass" end - it 'allows type to be passed in' do - ap = described_class.new('type' => 'bar') - expect(ap.type).to eq 'bar' + it "allows type to be passed in" do + ap = described_class.new("type" => "bar") + expect(ap.type).to eq "bar" end end - describe '#validate' do - it 'raises IllegalValueError if id is not URI' do + describe "#validate" do + it "raises IllegalValueError if id is not URI" do exp_err_msg = "id value must be a String containing a URI for #{described_class}" - subject['id'] = 'foo' + subject["id"] = "foo" expect { subject.validate }.to raise_error(IIIF::V3::Presentation::IllegalValueError, exp_err_msg) end - it 'raises IllegalValueError if id is not http(s)' do - subject['id'] = 'ftp://www.example.org' + it "raises IllegalValueError if id is not http(s)" do + subject["id"] = "ftp://www.example.org" exp_err_msg = "id must be an http(s) URI for #{described_class}" expect { subject.validate }.to raise_error(IIIF::V3::Presentation::IllegalValueError, exp_err_msg) end - it 'raises IllegalValueError for items entry that is not an Annotation' do - subject['id'] = 'http://example.com/iiif3/annotation_page/666' - subject['items'] = [IIIF::V3::Presentation::ImageResource.new, IIIF::V3::Presentation::Annotation.new] + it "raises IllegalValueError for items entry that is not an Annotation" do + subject["id"] = "http://example.com/iiif3/annotation_page/666" + subject["items"] = [IIIF::V3::Presentation::ImageResource.new, IIIF::V3::Presentation::Annotation.new] exp_err_msg = "All entries in the items list must be a IIIF::V3::Presentation::Annotation" expect { subject.validate }.to raise_error(IIIF::V3::Presentation::IllegalValueError, exp_err_msg) end end - describe 'realistic examples' do - let(:ap_id) { 'http://example.com/iiif3/annotation_page/666' } - let(:anno) { IIIF::V3::Presentation::Annotation.new( - 'id' => 'http://example.com/anno/666', - 'target' => 'http://example.com/canvas/abc' - )} + describe "realistic examples" do + let(:ap_id) { "http://example.com/iiif3/annotation_page/666" } + let(:anno) { + IIIF::V3::Presentation::Annotation.new( + "id" => "http://example.com/anno/666", + "target" => "http://example.com/canvas/abc" + ) + } - describe 'stanford (purl code)' do + describe "stanford (purl code)" do let(:anno_page) { anno_page = described_class.new - anno_page['id'] = ap_id + anno_page["id"] = ap_id anno_page.items << anno anno_page } - it 'validates' do - expect{anno_page.validate}.not_to raise_error + it "validates" do + expect { anno_page.validate }.not_to raise_error end - it 'has expected required values' do + it "has expected required values" do expect(anno_page.id).to eq ap_id - expect(anno_page['type']).to eq 'AnnotationPage' + expect(anno_page["type"]).to eq "AnnotationPage" end - it 'has expected additional values' do + it "has expected additional values" do expect(anno_page.items).to eq [anno] end end - describe 'two items' do - let(:anno2) { IIIF::V3::Presentation::Annotation.new( - 'id' => 'http://example.com/anno/333', - 'target' => 'http://example.com/canvas/abc' - )} + describe "two items" do + let(:anno2) { + IIIF::V3::Presentation::Annotation.new( + "id" => "http://example.com/anno/333", + "target" => "http://example.com/canvas/abc" + ) + } let(:anno_page) { anno_page = described_class.new - anno_page['id'] = ap_id + anno_page["id"] = ap_id anno_page.items = [anno, anno2] anno_page } - it 'validates' do - expect{anno_page.validate}.not_to raise_error + it "validates" do + expect { anno_page.validate }.not_to raise_error end - it 'has expected required values' do + it "has expected required values" do expect(anno_page.id).to eq ap_id - expect(anno_page['type']).to eq 'AnnotationPage' + expect(anno_page["type"]).to eq "AnnotationPage" end - it 'has expected additional values' do + it "has expected additional values" do expect(anno_page.items).to eq [anno, anno2] end end diff --git a/spec/unit/iiif/v3/presentation/annotation_spec.rb b/spec/unit/iiif/v3/presentation/annotation_spec.rb index e3f837e..1d27866 100644 --- a/spec/unit/iiif/v3/presentation/annotation_spec.rb +++ b/spec/unit/iiif/v3/presentation/annotation_spec.rb @@ -1,392 +1,408 @@ describe IIIF::V3::Presentation::Annotation do + let(:content_id) { "http://example.org/iiif/book1/res/tei-text-p1.xml" } + let(:content_type) { "dctypes:Text" } + let(:mimetype) { "application/tei+xml" } + let(:image_2_api_service) { + IIIF::V3::Presentation::Service.new({ + "id" => content_id, + "@id" => content_id, + "profile" => IIIF::V3::Presentation::Service::IIIF_IMAGE_V2_LEVEL1_PROFILE + }) + } + let(:img_content_resource) { + IIIF::V3::Presentation::ImageResource.new( + "id" => content_id, + "type" => content_type, + "format" => mimetype, + "service" => [image_2_api_service] + ) + } - let(:content_id) { 'http://example.org/iiif/book1/res/tei-text-p1.xml' } - let(:content_type) { 'dctypes:Text' } - let(:mimetype) { 'application/tei+xml' } - let(:image_2_api_service) { IIIF::V3::Presentation::Service.new({ - 'id' => content_id, - '@id' => content_id, - 'profile' => IIIF::V3::Presentation::Service::IIIF_IMAGE_V2_LEVEL1_PROFILE - })} - let(:img_content_resource) { IIIF::V3::Presentation::ImageResource.new( - 'id' => content_id, - 'type' => content_type, - 'format' => mimetype, - 'service' => [image_2_api_service] - )} - - describe '#required_keys' do - %w{ type id motivation target }.each do |k| + describe "#required_keys" do + %w[type id motivation target].each do |k| it k do expect(subject.required_keys).to include(k) end end end - describe '#prohibited_keys' do - it 'contains the expected key names' do + describe "#prohibited_keys" do + it "contains the expected key names" do keys = described_class::PAGING_PROPERTIES + described_class::CONTENT_RESOURCE_PROPERTIES + - %w{ - nav_date - viewing_direction - start_canvas - content_annotations - } - expect(subject.prohibited_keys).to include(*keys) - end + %w[ + nav_date + viewing_direction + start_canvas + content_annotations + ] + expect(subject.prohibited_keys).to include(*keys) + end end - describe '#any_type_keys' do - it 'body' do - expect(subject.any_type_keys).to include('body') + describe "#any_type_keys" do + it "body" do + expect(subject.any_type_keys).to include("body") end - it 'target' do - expect(subject.any_type_keys).to include('target') + it "target" do + expect(subject.any_type_keys).to include("target") end end - describe '#uri_only_keys' do - it 'id' do - expect(subject.uri_only_keys).to include('id') + describe "#uri_only_keys" do + it "id" do + expect(subject.uri_only_keys).to include("id") end end - describe '#string_only_keys' do - it 'time_mode' do - expect(subject.string_only_keys).to include('time_mode') + describe "#string_only_keys" do + it "time_mode" do + expect(subject.string_only_keys).to include("time_mode") end end - describe '#legal_time_mode_values' do - it 'contains the expected values' do - expect(subject.legal_time_mode_values).to contain_exactly('trim', 'scale', 'loop') + describe "#legal_time_mode_values" do + it "contains the expected values" do + expect(subject.legal_time_mode_values).to contain_exactly("trim", "scale", "loop") end end - describe '#legal_viewing_hint_values' do - it 'contains none' do - expect(subject.legal_viewing_hint_values).to contain_exactly('none') + describe "#legal_viewing_hint_values" do + it "contains none" do + expect(subject.legal_viewing_hint_values).to contain_exactly("none") end end - describe '#initialize' do - it 'sets type to Annotation by default' do - expect(subject['type']).to eq 'Annotation' + describe "#initialize" do + it "sets type to Annotation by default" do + expect(subject["type"]).to eq "Annotation" end - it 'allows subclasses to override type' do + it "allows subclasses to override type" do subclass = Class.new(described_class) do - def initialize(hsh={}) - hsh = { 'type' => 'a:SubClass' } - super(hsh) + def initialize(_hsh = {}) + super({"type" => "a:SubClass"}) end end sub = subclass.new - expect(sub['type']).to eq 'a:SubClass' + expect(sub["type"]).to eq "a:SubClass" end - it 'sets motivation to painting by default' do - expect(subject['motivation']).to eq 'painting' + it "sets motivation to painting by default" do + expect(subject["motivation"]).to eq "painting" end - it 'allows motivation to be passed in' do - my_anno = described_class.new('motivation' => 'foo') - expect(my_anno.motivation).to eq 'foo' + it "allows motivation to be passed in" do + my_anno = described_class.new("motivation" => "foo") + expect(my_anno.motivation).to eq "foo" end - it 'allows type to be passed in' do - my_anno = described_class.new('type' => 'bar') - expect(my_anno.type).to eq 'bar' + it "allows type to be passed in" do + my_anno = described_class.new("type" => "bar") + expect(my_anno.type).to eq "bar" end end - describe '#validate' do + describe "#validate" do before(:each) do - subject['id'] = 'http://example.org/iiif/anno/1s' - subject['target'] = 'foo' + subject["id"] = "http://example.org/iiif/anno/1s" + subject["target"] = "foo" end - it 'raises IllegalValueError if id is not URI' do + it "raises IllegalValueError if id is not URI" do exp_err_msg = "id value must be a String containing a URI for #{described_class}" - subject['id'] = 'foo' + subject["id"] = "foo" expect { subject.validate }.to raise_error(IIIF::V3::Presentation::IllegalValueError, exp_err_msg) end - it 'raises IllegalValueError if time_mode isn\'t an allowable value' do + it "raises IllegalValueError if time_mode isn't an allowable value" do exp_err_msg = "timeMode for #{described_class} must be one of [\"trim\", \"scale\", \"loop\"]." - subject['time_mode'] = 'foo' + subject["time_mode"] = "foo" expect { subject.validate }.to raise_error IIIF::V3::Presentation::IllegalValueError, exp_err_msg end - describe 'body is a kind of IIIF::V3::Presentation::ImageResource' do + describe "body is a kind of IIIF::V3::Presentation::ImageResource" do let(:img_body_anno) { - subject['id'] = 'http://example.org/iiif/anno/1s' - subject['target'] = 'foo' - subject['body'] = img_content_resource + subject["id"] = "http://example.org/iiif/anno/1s" + subject["target"] = "foo" + subject["body"] = img_content_resource subject } it 'raises IllegalValueError if motivation isn\'t "painting"' do exp_err_msg = "#{described_class} motivation must be 'painting' when body is a kind of IIIF::V3::Presentation::ImageResource" - img_body_anno['motivation'] = 'foo' + img_body_anno["motivation"] = "foo" expect { img_body_anno.validate }.to raise_error IIIF::V3::Presentation::IllegalValueError, exp_err_msg end let(:img_resource_without_id) { IIIF::V3::Presentation::ImageResource.new( - 'type' => content_type, - 'format' => mimetype - )} + "type" => content_type, + "format" => mimetype + ) + } let(:http_uri_err_msg) { "when #{described_class} body is a kind of IIIF::V3::Presentation::ImageResource, ImageResource id must be an http(s) URI" } - it 'raises IllegalValueError if no id field in ImageResource' do + it "raises IllegalValueError if no id field in ImageResource" do img_body_anno.body = img_resource_without_id expect { img_body_anno.validate }.to raise_error IIIF::V3::Presentation::IllegalValueError, http_uri_err_msg end - it 'raises IllegalValueError if id in ImageResource isn\'t URI' do - img_resource_without_id['id'] = 'foo' + it "raises IllegalValueError if id in ImageResource isn't URI" do + img_resource_without_id["id"] = "foo" img_body_anno.body = img_resource_without_id expect { img_body_anno.validate }.to raise_error IIIF::V3::Presentation::IllegalValueError, http_uri_err_msg end - it 'raises IllegalValueError if id in ImageResource isn\'t http(s) URI' do - img_resource_without_id['id'] = 'ftp://example.com/somewhere' + it "raises IllegalValueError if id in ImageResource isn't http(s) URI" do + img_resource_without_id["id"] = "ftp://example.com/somewhere" img_body_anno.body = img_resource_without_id expect { img_body_anno.validate }.to raise_error IIIF::V3::Presentation::IllegalValueError, http_uri_err_msg end end end - describe 'realistic examples' do - let(:anno_id) { 'http://example.org/iiif/annoation/abc666'} - let(:target_id) { 'http://example.org/iiif/canvas/abc666'} + describe "realistic examples" do + let(:anno_id) { "http://example.org/iiif/annoation/abc666" } + let(:target_id) { "http://example.org/iiif/canvas/abc666" } - describe 'stanford (purl code)' do + describe "stanford (purl code)" do let(:anno) { anno = described_class.new - anno['id'] = anno_id - anno['target'] = target_id + anno["id"] = anno_id + anno["target"] = target_id anno.body = img_content_resource anno } - it 'validates' do - expect{anno.validate}.not_to raise_error + it "validates" do + expect { anno.validate }.not_to raise_error end - it 'has expected required values' do + it "has expected required values" do expect(anno.id).to eq anno_id - expect(anno['type']).to eq 'Annotation' - expect(anno['motivation']).to eq 'painting' - expect(anno['target']).to eq target_id + expect(anno["type"]).to eq "Annotation" + expect(anno["motivation"]).to eq "painting" + expect(anno["target"]).to eq target_id end - it 'has expected additional values' do - expect(anno['body']).to eq img_content_resource + it "has expected additional values" do + expect(anno["body"]).to eq img_content_resource end end - describe 'from http://prezi3.iiif.io/api/presentation/3.0' do - describe 'body is image_resource with height and width' do - let(:img_type) { 'dctypes:Image' } - let(:img_mime) { 'image/jpeg' } + describe "from http://prezi3.iiif.io/api/presentation/3.0" do + describe "body is image_resource with height and width" do + let(:img_type) { "dctypes:Image" } + let(:img_mime) { "image/jpeg" } let(:img_h) { 2000 } let(:img_w) { 1500 } - let(:img_hw_resource) do + let(:img_hw_resource) do IIIF::V3::Presentation::ImageResource.new( - 'id' => content_id, - 'type' => img_type, - 'format' => img_mime, - 'height' => img_h, - 'width' => img_w, - 'service' => [image_2_api_service] + "id" => content_id, + "type" => img_type, + "format" => img_mime, + "height" => img_h, + "width" => img_w, + "service" => [image_2_api_service] ) end let(:my_anno) { anno = described_class.new - anno['id'] = anno_id - anno['target'] = target_id + anno["id"] = anno_id + anno["target"] = target_id anno.body = img_hw_resource anno } - it 'validates' do - expect{my_anno.validate}.not_to raise_error + it "validates" do + expect { my_anno.validate }.not_to raise_error end - it 'has expected additional values' do - expect(my_anno['body']).to eq img_hw_resource - expect(my_anno['body']['height']).to eq img_h - expect(my_anno['body']['width']).to eq img_w + it "has expected additional values" do + expect(my_anno["body"]).to eq img_hw_resource + expect(my_anno["body"]["height"]).to eq img_h + expect(my_anno["body"]["width"]).to eq img_w end - describe 'and service with height and width and tiles' do - let(:tiles_val) { [{"width" => 512, "scaleFactors" => [1,2,4,8,16]}] } + describe "and service with height and width and tiles" do + let(:tiles_val) { [{"width" => 512, "scaleFactors" => [1, 2, 4, 8, 16]}] } let(:service) do s = image_2_api_service - s['height'] = 8000 - s['width'] = 6000 - s['tiles'] = tiles_val + s["height"] = 8000 + s["width"] = 6000 + s["tiles"] = tiles_val [s] end - it 'validates' do - img_hw_resource['service'] = service - expect{my_anno.validate}.not_to raise_error + it "validates" do + img_hw_resource["service"] = service + expect { my_anno.validate }.not_to raise_error end it "body['service'] has expected additional values'" do - annotation_service = my_anno['body']['service'].first + annotation_service = my_anno["body"]["service"].first expect(annotation_service).to eq service.first - expect(annotation_service['height']).to eq 8000 - expect(annotation_service['width']).to eq 6000 - expect(annotation_service['tiles']).to eq tiles_val + expect(annotation_service["height"]).to eq 8000 + expect(annotation_service["width"]).to eq 6000 + expect(annotation_service["tiles"]).to eq tiles_val end end end end - describe 'from digerati' do - describe 'anno body is audio' do - let(:body_id) { 'http://example.org/iiif/foo2.mp3' } - let(:body_type) { 'Audio' } - let(:audio_res) { IIIF::V3::Presentation::Resource.new( - 'id' => body_id, - 'type' => body_type - )} + describe "from digerati" do + describe "anno body is audio" do + let(:body_id) { "http://example.org/iiif/foo2.mp3" } + let(:body_type) { "Audio" } + let(:audio_res) { + IIIF::V3::Presentation::Resource.new( + "id" => body_id, + "type" => body_type + ) + } let(:my_anno) { anno = described_class.new - anno['id'] = anno_id - anno['target'] = target_id + anno["id"] = anno_id + anno["target"] = target_id anno.body = audio_res anno } - it 'validates' do - expect{my_anno.validate}.not_to raise_error + it "validates" do + expect { my_anno.validate }.not_to raise_error end - it 'has expected required values' do - expect(my_anno['type']).to eq 'Annotation' + it "has expected required values" do + expect(my_anno["type"]).to eq "Annotation" expect(my_anno.id).to eq anno_id - expect(my_anno['motivation']).to eq 'painting' - expect(my_anno['target']).to eq target_id + expect(my_anno["motivation"]).to eq "painting" + expect(my_anno["target"]).to eq target_id end - it 'has expected additional values' do - expect(my_anno['body']).to eq audio_res - expect(my_anno['body']['type']).to eq body_type - expect(my_anno['body']['id']).to eq body_id + it "has expected additional values" do + expect(my_anno["body"]).to eq audio_res + expect(my_anno["body"]["type"]).to eq body_type + expect(my_anno["body"]["id"]).to eq body_id end end - describe 'anno body is video' do - let(:body_id) { 'http://example.org/foo.webm' } - let(:body_type) { 'Video' } - let(:body_mime) { 'video/webm' } - let(:video_res) { IIIF::V3::Presentation::Resource.new( - 'id' => body_id, - 'type' => body_type, - 'format' => body_mime - )} + describe "anno body is video" do + let(:body_id) { "http://example.org/foo.webm" } + let(:body_type) { "Video" } + let(:body_mime) { "video/webm" } + let(:video_res) { + IIIF::V3::Presentation::Resource.new( + "id" => body_id, + "type" => body_type, + "format" => body_mime + ) + } let(:my_anno) { anno = described_class.new - anno['id'] = anno_id - anno['target'] = target_id + anno["id"] = anno_id + anno["target"] = target_id anno.body = video_res anno } - it 'validates' do - expect{my_anno.validate}.not_to raise_error + it "validates" do + expect { my_anno.validate }.not_to raise_error end - it 'has expected body values' do - expect(my_anno['body']).to eq video_res - expect(my_anno['body']['type']).to eq body_type - expect(my_anno['body']['id']).to eq body_id - expect(my_anno['body']['format']).to eq body_mime + it "has expected body values" do + expect(my_anno["body"]).to eq video_res + expect(my_anno["body"]["type"]).to eq body_type + expect(my_anno["body"]["id"]).to eq body_id + expect(my_anno["body"]["format"]).to eq body_mime end end - describe 'anno body is 3d object' do - let(:body_id) { 'http://files.universalviewer.io/manifests/nelis/animal-skull/animal-skull.json' } - let(:body_type) { 'PhysicalObject' } - let(:body_mime) { 'application/vnd.threejs+json' } - let(:body_label) { 'Animal Skull' } - let(:body_res) { IIIF::V3::Presentation::Resource.new( - 'id' => body_id, - 'type' => body_type, - 'format' => body_mime, - 'label' => body_label - )} + describe "anno body is 3d object" do + let(:body_id) { "http://files.universalviewer.io/manifests/nelis/animal-skull/animal-skull.json" } + let(:body_type) { "PhysicalObject" } + let(:body_mime) { "application/vnd.threejs+json" } + let(:body_label) { "Animal Skull" } + let(:body_res) { + IIIF::V3::Presentation::Resource.new( + "id" => body_id, + "type" => body_type, + "format" => body_mime, + "label" => body_label + ) + } let(:my_anno) { anno = described_class.new - anno['id'] = anno_id - anno['target'] = target_id + anno["id"] = anno_id + anno["target"] = target_id anno.body = body_res anno } - it 'validates' do - expect{my_anno.validate}.not_to raise_error + it "validates" do + expect { my_anno.validate }.not_to raise_error end - it 'has expected body values' do - expect(my_anno['body']).to eq body_res - expect(my_anno['body']['type']).to eq body_type - expect(my_anno['body']['id']).to eq body_id - expect(my_anno['body']['format']).to eq body_mime - expect(my_anno['body']['label']).to eq body_label + it "has expected body values" do + expect(my_anno["body"]).to eq body_res + expect(my_anno["body"]["type"]).to eq body_type + expect(my_anno["body"]["id"]).to eq body_id + expect(my_anno["body"]["format"]).to eq body_mime + expect(my_anno["body"]["label"]).to eq body_label end end - describe 'anno body is pdf' do - let(:body_id) { 'http://example.org/iiif/some-document.pdf' } - let(:body_type) { 'Document' } - let(:body_mime) { 'application/pdf' } - let(:body_res) { IIIF::V3::Presentation::Resource.new( - 'id' => body_id, - 'type' => body_type, - 'format' => body_mime - )} + describe "anno body is pdf" do + let(:body_id) { "http://example.org/iiif/some-document.pdf" } + let(:body_type) { "Document" } + let(:body_mime) { "application/pdf" } + let(:body_res) { + IIIF::V3::Presentation::Resource.new( + "id" => body_id, + "type" => body_type, + "format" => body_mime + ) + } let(:my_anno) { anno = described_class.new - anno['id'] = anno_id - anno['target'] = target_id + anno["id"] = anno_id + anno["target"] = target_id anno.body = body_res anno } - it 'validates' do - expect{my_anno.validate}.not_to raise_error + it "validates" do + expect { my_anno.validate }.not_to raise_error end - it 'has expected body values' do - expect(my_anno['body']).to eq body_res - expect(my_anno['body']['type']).to eq body_type - expect(my_anno['body']['id']).to eq body_id - expect(my_anno['body']['format']).to eq body_mime + it "has expected body values" do + expect(my_anno["body"]).to eq body_res + expect(my_anno["body"]["type"]).to eq body_type + expect(my_anno["body"]["id"]).to eq body_id + expect(my_anno["body"]["format"]).to eq body_mime end end - describe 'anno body is choice (of 2 videos)' do - let(:body_type) { 'Video' } - let(:body1_id) { 'http://example.org/foo.mp4f' } - let(:body1_mime) { 'video/mp4; codec..xxxxx' } - let(:body1_res) { IIIF::V3::Presentation::Resource.new( - 'id' => body1_id, - 'type' => body_type, - 'format' => body1_mime - )} - let(:body2_id) { 'http://example.org/foo.webm' } - let(:body2_mime) { 'video/webm' } - let(:body2_res) { IIIF::V3::Presentation::Resource.new( - 'id' => body2_id, - 'type' => body_type, - 'format' => body2_mime - )} - let(:body_res) { IIIF::V3::Presentation::Choice.new( - 'items' => [body1_res, body2_res], - 'choiceHint' => 'client' - )} + describe "anno body is choice (of 2 videos)" do + let(:body_type) { "Video" } + let(:body1_id) { "http://example.org/foo.mp4f" } + let(:body1_mime) { "video/mp4; codec..xxxxx" } + let(:body1_res) { + IIIF::V3::Presentation::Resource.new( + "id" => body1_id, + "type" => body_type, + "format" => body1_mime + ) + } + let(:body2_id) { "http://example.org/foo.webm" } + let(:body2_mime) { "video/webm" } + let(:body2_res) { + IIIF::V3::Presentation::Resource.new( + "id" => body2_id, + "type" => body_type, + "format" => body2_mime + ) + } + let(:body_res) { + IIIF::V3::Presentation::Choice.new( + "items" => [body1_res, body2_res], + "choiceHint" => "client" + ) + } let(:my_anno) { anno = described_class.new - anno['id'] = anno_id - anno['target'] = target_id + anno["id"] = anno_id + anno["target"] = target_id anno.body = body_res anno } - it 'validates' do - expect{my_anno.validate}.not_to raise_error + it "validates" do + expect { my_anno.validate }.not_to raise_error end - it 'has expected body values' do - expect(my_anno['body']).to eq body_res - expect(my_anno['body'].keys.size).to eq 3 - expect(my_anno['body']['type']).to eq 'Choice' - expect(my_anno['body'].choiceHint).to eq 'client' - expect(my_anno['body']['items']).to eq [body1_res, body2_res] + it "has expected body values" do + expect(my_anno["body"]).to eq body_res + expect(my_anno["body"].keys.size).to eq 3 + expect(my_anno["body"]["type"]).to eq "Choice" + expect(my_anno["body"].choiceHint).to eq "client" + expect(my_anno["body"]["items"]).to eq [body1_res, body2_res] end end end end - end diff --git a/spec/unit/iiif/v3/presentation/canvas_spec.rb b/spec/unit/iiif/v3/presentation/canvas_spec.rb index fad931d..63a2af0 100644 --- a/spec/unit/iiif/v3/presentation/canvas_spec.rb +++ b/spec/unit/iiif/v3/presentation/canvas_spec.rb @@ -1,331 +1,349 @@ describe IIIF::V3::Presentation::Canvas do + describe "#required_keys" do + %w[type id label].each do |k| + it k do + expect(subject.required_keys).to include(k) + end + end + end - describe '#required_keys' do - %w{ type id label }.each do |k| - it k do - expect(subject.required_keys).to include(k) - end - end - end - - describe '#prohibited_keys' do - it 'contains the expected key names' do - keys = described_class::PAGING_PROPERTIES + - %w{ - viewing_direction - format - nav_date - start_canvas - content_annotations - } - expect(subject.prohibited_keys).to include(*keys) - end + describe "#prohibited_keys" do + it "contains the expected key names" do + keys = described_class::PAGING_PROPERTIES + + %w[ + viewing_direction + format + nav_date + start_canvas + content_annotations + ] + expect(subject.prohibited_keys).to include(*keys) + end end - describe '#int_only_keys' do - it 'depth (for 3d objects)' do - expect(subject.int_only_keys).to include('depth') + describe "#int_only_keys" do + it "depth (for 3d objects)" do + expect(subject.int_only_keys).to include("depth") end end - describe '#array_only_keys' do - it 'content' do - expect(subject.array_only_keys).to include('content') + describe "#array_only_keys" do + it "content" do + expect(subject.array_only_keys).to include("content") end end - describe '#legal_viewing_hint_values' do - it 'contains the expected values' do - expect(subject.legal_viewing_hint_values).to contain_exactly('paged', 'continuous', 'non-paged', 'facing-pages', 'auto-advance') + describe "#legal_viewing_hint_values" do + it "contains the expected values" do + expect(subject.legal_viewing_hint_values).to contain_exactly("paged", "continuous", "non-paged", "facing-pages", "auto-advance") end end - describe '#initialize' do - it 'sets type to Canvas by default' do - expect(subject['type']).to eq 'Canvas' + describe "#initialize" do + it "sets type to Canvas by default" do + expect(subject["type"]).to eq "Canvas" end - it 'allows subclasses to override type' do + it "allows subclasses to override type" do subclass = Class.new(described_class) do - def initialize(hsh={}) - hsh = { 'type' => 'a:SubClass' } - super(hsh) + def initialize(_hsh = {}) + super({"type" => "a:SubClass"}) end end sub = subclass.new - expect(sub['type']).to eq 'a:SubClass' + expect(sub["type"]).to eq "a:SubClass" end end - describe '#validate' do - let(:canvas_id) { 'http://example.org/iiif/book1/canvas/c1' } + describe "#validate" do + let(:canvas_id) { "http://example.org/iiif/book1/canvas/c1" } let(:exp_id_err_msg) { "id must be an http(s) URI without a fragment for #{described_class}" } before(:each) do - subject['id'] = canvas_id - subject['label'] = 'foo' + subject["id"] = canvas_id + subject["label"] = "foo" end - it 'raises IllegalValueError if id is not URI' do - subject['id'] = 'foo' + it "raises IllegalValueError if id is not URI" do + subject["id"] = "foo" expect { subject.validate }.to raise_error(IIIF::V3::Presentation::IllegalValueError, exp_id_err_msg) end - it 'raises IllegalValueError if id is not http(s)' do - subject['id'] = 'ftp://www.example.org' + it "raises IllegalValueError if id is not http(s)" do + subject["id"] = "ftp://www.example.org" expect { subject.validate }.to raise_error(IIIF::V3::Presentation::IllegalValueError, exp_id_err_msg) end - it 'raises IllegalValueError if id has a fragment' do - subject['id'] = 'http://www.example.org#foo' + it "raises IllegalValueError if id has a fragment" do + subject["id"] = "http://www.example.org#foo" expect { subject.validate }.to raise_error(IIIF::V3::Presentation::IllegalValueError, exp_id_err_msg) end # let(:exp_extent_err_msg) { "#{described_class} must have (a height and a width) and/or a duration" } # (see sul-dlss/purl/issues/169) let(:exp_extent_err_msg) { "#{described_class} requires both height and width or neither" } - it 'raises IllegalValueError if height is a string' do - subject['height'] = 'foo' + it "raises IllegalValueError if height is a string" do + subject["height"] = "foo" expect { subject.validate }.to raise_error(IIIF::V3::Presentation::IllegalValueError, exp_extent_err_msg) end - it 'raises IllegalValueError if height but no width' do - subject['height'] = 666 + it "raises IllegalValueError if height but no width" do + subject["height"] = 666 expect { subject.validate }.to raise_error(IIIF::V3::Presentation::IllegalValueError, exp_extent_err_msg) end - it 'raises IllegalValueError if width but no height' do - subject['width'] = 666 - subject['duration'] = 66.6 + it "raises IllegalValueError if width but no height" do + subject["width"] = 666 + subject["duration"] = 66.6 expect { subject.validate }.to raise_error(IIIF::V3::Presentation::IllegalValueError, exp_extent_err_msg) end - it 'raises IllegalValueError if no width, height or duration' do + it "raises IllegalValueError if no width, height or duration" do # (see sul-dlss/purl/issues/169) - skip('while this is in the current v3 spec, it does not make sense for some content (e.g. txt files)') + skip("while this is in the current v3 spec, it does not make sense for some content (e.g. txt files)") expect { subject.validate }.to raise_error(IIIF::V3::Presentation::IllegalValueError, exp_extent_err_msg) end - it 'allows width, height and duration' do - subject['width'] = 666 - subject['height'] = 666 - subject['duration'] = 66.6 + it "allows width, height and duration" do + subject["width"] = 666 + subject["height"] = 666 + subject["duration"] = 66.6 expect { subject.validate }.not_to raise_error end - it 'raises IllegalValueError for content entry that is not an AnnotationPage' do - subject['content'] = [IIIF::V3::Presentation::AnnotationPage.new, IIIF::V3::Presentation::Annotation.new] + it "raises IllegalValueError for content entry that is not an AnnotationPage" do + subject["content"] = [IIIF::V3::Presentation::AnnotationPage.new, IIIF::V3::Presentation::Annotation.new] exp_err_msg = "All entries in the content list must be a IIIF::V3::Presentation::AnnotationPage" expect { subject.validate }.to raise_error(IIIF::V3::Presentation::IllegalValueError, exp_err_msg) end - it 'IllegalValueError for content with annotation target not the canvas id' do + it "IllegalValueError for content with annotation target not the canvas id" do anno = IIIF::V3::Presentation::Annotation.new( - 'id' => 'http://example.com/anno/666', - 'target' => canvas_id) + "id" => "http://example.com/anno/666", + "target" => canvas_id + ) anno_page = IIIF::V3::Presentation::AnnotationPage.new( - 'id' => "http://example.org/iiif/book1/page/p1/1", - 'items' => [anno]) - subject['content'] = [anno_page] + "id" => "http://example.org/iiif/book1/page/p1/1", + "items" => [anno] + ) + subject["content"] = [anno_page] expect { subject.validate }.not_to raise_error - anno['target'] = 'http://example.com/canvas/abc' - exp_err_msg = 'URI of the canvas must be repeated in the target field of included Annotations' + anno["target"] = "http://example.com/canvas/abc" + exp_err_msg = "URI of the canvas must be repeated in the target field of included Annotations" expect { subject.validate }.to raise_error(IIIF::V3::Presentation::IllegalValueError, exp_err_msg) end end - describe 'realistic examples' do - let(:canvas_id) { 'http://example.org/iiif/book1/canvas/c1' } - let(:minimal_canvas_object) { described_class.new({ - "id" => canvas_id, - 'label' => {"en" => ["so minimal it's not here"]}, - 'height' => 1000, - 'width' => 1000 - })} - let(:anno_page) { IIIF::V3::Presentation::AnnotationPage.new( - "id" => "http://example.org/iiif/book1/page/p1/1", - 'items' => [] - )} - describe 'minimal canvas' do - it 'validates' do - expect{minimal_canvas_object.validate}.not_to raise_error + describe "realistic examples" do + let(:canvas_id) { "http://example.org/iiif/book1/canvas/c1" } + let(:minimal_canvas_object) { + described_class.new({ + "id" => canvas_id, + "label" => {"en" => ["so minimal it's not here"]}, + "height" => 1000, + "width" => 1000 + }) + } + let(:anno_page) { + IIIF::V3::Presentation::AnnotationPage.new( + "id" => "http://example.org/iiif/book1/page/p1/1", + "items" => [] + ) + } + describe "minimal canvas" do + it "validates" do + expect { minimal_canvas_object.validate }.not_to raise_error end - it 'has expected required values' do + it "has expected required values" do expect(minimal_canvas_object.type).to eq described_class::TYPE expect(minimal_canvas_object.id).to eq canvas_id - expect(minimal_canvas_object.label['en']).to include "so minimal it's not here" + expect(minimal_canvas_object.label["en"]).to include "so minimal it's not here" expect(minimal_canvas_object.height).to eq 1000 expect(minimal_canvas_object.width).to eq 1000 end end - describe 'minimal with empty content' do + describe "minimal with empty content" do let(:canvas_object) { - minimal_canvas_object['content'] = [] + minimal_canvas_object["content"] = [] minimal_canvas_object } - it 'validates' do - expect{canvas_object.validate}.not_to raise_error + it "validates" do + expect { canvas_object.validate }.not_to raise_error end - it 'has empty array for content' do + it "has empty array for content" do expect(canvas_object.content).to eq [] end end - describe 'minimal with content' do + describe "minimal with content" do let(:canvas_object) { - minimal_canvas_object['content'] = [anno_page, anno_page] + minimal_canvas_object["content"] = [anno_page, anno_page] minimal_canvas_object } - it 'validates' do - expect{canvas_object.validate}.not_to raise_error + it "validates" do + expect { canvas_object.validate }.not_to raise_error end - it 'has content value' do + it "has content value" do expect(canvas_object.content.size).to eq 2 expect(canvas_object.content).to eq [anno_page, anno_page] end - describe 'stanford (purl code)' do + describe "stanford (purl code)" do let(:canvas_object) { c = described_class.new - c['id'] = canvas_id - c.label = {'en' => ['label']} + c["id"] = canvas_id + c.label = {"en" => ["label"]} c.content << anno_page c } - describe 'non-image' do - it 'validates' do - expect{canvas_object.validate}.not_to raise_error + describe "non-image" do + it "validates" do + expect { canvas_object.validate }.not_to raise_error end - it 'has expected required values' do + it "has expected required values" do expect(canvas_object.type).to eq described_class::TYPE expect(canvas_object.id).to eq canvas_id - expect(canvas_object.label['en']).to include "label" + expect(canvas_object.label["en"]).to include "label" end - it 'has expected additional values' do + it "has expected additional values" do expect(canvas_object.content).to eq [anno_page] end end - describe 'image' do + describe "image" do let(:img_canvas) { canvas_object.height = 666 canvas_object.width = 888 canvas_object } - it 'validates' do - expect{img_canvas.validate}.not_to raise_error + it "validates" do + expect { img_canvas.validate }.not_to raise_error end - it 'has expected required values' do + it "has expected required values" do expect(img_canvas.type).to eq described_class::TYPE expect(img_canvas.id).to eq canvas_id - expect(img_canvas.label['en']).to include "label" + expect(img_canvas.label["en"]).to include "label" expect(img_canvas.height).to eq 666 expect(img_canvas.width).to eq 888 end - it 'has expected additional values' do + it "has expected additional values" do expect(img_canvas.content).to eq [anno_page] end end end - describe 'file object' do - describe 'without extent info' do - let(:file_object) { described_class.new({ - "id" => "https://example.org/bd742gh0511/iiif3/canvas/bd742gh0511_1", - "label" => {"en" => ["File 1"]}, - "content" => [anno_page] - })} - it 'validates' do - expect{file_object.validate}.not_to raise_error + describe "file object" do + describe "without extent info" do + let(:file_object) { + described_class.new({ + "id" => "https://example.org/bd742gh0511/iiif3/canvas/bd742gh0511_1", + "label" => {"en" => ["File 1"]}, + "content" => [anno_page] + }) + } + it "validates" do + expect { file_object.validate }.not_to raise_error end end end - describe 'image object' do - describe 'without extent info' do - let(:image_object) { described_class.new({ - "id" => "https://example.org/yv090xk3108/iiif3/canvas/yv090xk3108_1", - "label" => {"en" => ["image"]}, - "content" => [anno_page] - })} - it 'validates' do - expect{image_object.validate}.not_to raise_error + describe "image object" do + describe "without extent info" do + let(:image_object) { + described_class.new({ + "id" => "https://example.org/yv090xk3108/iiif3/canvas/yv090xk3108_1", + "label" => {"en" => ["image"]}, + "content" => [anno_page] + }) + } + it "validates" do + expect { image_object.validate }.not_to raise_error end end - describe 'with extent given' do - let(:image_object) { described_class.new({ - "id" => "https://example.org/yy816tv6021/iiif3/canvas/yy816tv6021_3", - "label" => {"en" => ["Image of media (1 of 2)"]}, - "height" => 3456, - "width" => 5184, - "content" => [anno_page] - })} - it 'validates' do - expect{image_object.validate}.not_to raise_error + describe "with extent given" do + let(:image_object) { + described_class.new({ + "id" => "https://example.org/yy816tv6021/iiif3/canvas/yy816tv6021_3", + "label" => {"en" => ["Image of media (1 of 2)"]}, + "height" => 3456, + "width" => 5184, + "content" => [anno_page] + }) + } + it "validates" do + expect { image_object.validate }.not_to raise_error end end end - describe 'audio object' do - describe 'without duration' do - let(:canvas_for_audio) { described_class.new({ - "id" => "https://example.org/xk681bt2506/iiif3/canvas/xk681bt2506_1", - "label" => {"en" => ["Audio file 1"]}, - "content" => [anno_page] - })} - it 'validates' do - expect{canvas_for_audio.validate}.not_to raise_error + describe "audio object" do + describe "without duration" do + let(:canvas_for_audio) { + described_class.new({ + "id" => "https://example.org/xk681bt2506/iiif3/canvas/xk681bt2506_1", + "label" => {"en" => ["Audio file 1"]}, + "content" => [anno_page] + }) + } + it "validates" do + expect { canvas_for_audio.validate }.not_to raise_error end end - describe 'digerati example' do - let(:canvas_for_audio) { described_class.new({ - "id" => "http://tomcrane.github.io/scratch/manifests/3/canvas/2", - "label" => "Track 2", - 'summary' => { - 'en' => ['foo'] - }, - "duration" => 45, - "content" => [anno_page] - })} - it 'validates' do - expect{canvas_for_audio.validate}.not_to raise_error + describe "digerati example" do + let(:canvas_for_audio) { + described_class.new({ + "id" => "http://tomcrane.github.io/scratch/manifests/3/canvas/2", + "label" => "Track 2", + "summary" => { + "en" => ["foo"] + }, + "duration" => 45, + "content" => [anno_page] + }) + } + it "validates" do + expect { canvas_for_audio.validate }.not_to raise_error end - it 'duration' do + it "duration" do expect(canvas_for_audio.duration).to eq 45 end - it 'summary' do - expect(canvas_for_audio.summary['en'].first).to eq 'foo' + it "summary" do + expect(canvas_for_audio.summary["en"].first).to eq "foo" end end end - describe '3d object' do - let(:canvas_3d_object) { described_class.new({ - "id" => "http://tomcrane.github.io/scratch/manifests/3/canvas/3d", - "thumbnail" => [{'id' => "http://files.universalviewer.io/manifests/nelis/animal-skull/thumb.jpg", - 'type' => 'Image'}], - "width" => 10000, - "height" => 10000, - "depth" => 10000, - "label" => "A stage for an object", - "content" => [anno_page] - })} - it 'validates' do - expect{canvas_3d_object.validate}.not_to raise_error + describe "3d object" do + let(:canvas_3d_object) { + described_class.new({ + "id" => "http://tomcrane.github.io/scratch/manifests/3/canvas/3d", + "thumbnail" => [{"id" => "http://files.universalviewer.io/manifests/nelis/animal-skull/thumb.jpg", + "type" => "Image"}], + "width" => 10000, + "height" => 10000, + "depth" => 10000, + "label" => "A stage for an object", + "content" => [anno_page] + }) + } + it "validates" do + expect { canvas_3d_object.validate }.not_to raise_error end - it 'thumbnail' do - expect(canvas_3d_object.thumbnail).to eq [{'id' => "http://files.universalviewer.io/manifests/nelis/animal-skull/thumb.jpg", 'type' => 'Image'}] + it "thumbnail" do + expect(canvas_3d_object.thumbnail).to eq [{"id" => "http://files.universalviewer.io/manifests/nelis/animal-skull/thumb.jpg", "type" => "Image"}] end - it 'depth' do + it "depth" do expect(canvas_3d_object.depth).to eq 10000 end end - describe 'video object' do - describe 'with extent info' do - let(:canvas_for_video) { described_class.new({ - "id" => "http://tomcrane.github.io/scratch/manifests/3/canvas/1", - "label" => "Associate multiple Video representations as Choice", - "height" => 1000, - "width" => 1000, - "duration" => 100, - "content" => [anno_page] - }) } - it 'validates' do - expect{canvas_for_video.validate}.not_to raise_error + describe "video object" do + describe "with extent info" do + let(:canvas_for_video) { + described_class.new({ + "id" => "http://tomcrane.github.io/scratch/manifests/3/canvas/1", + "label" => "Associate multiple Video representations as Choice", + "height" => 1000, + "width" => 1000, + "duration" => 100, + "content" => [anno_page] + }) + } + it "validates" do + expect { canvas_for_video.validate }.not_to raise_error end - it 'height, width, duration' do + it "height, width, duration" do expect(canvas_for_video.height).to eq 1000 expect(canvas_for_video.width).to eq 1000 expect(canvas_for_video.duration).to eq 100 diff --git a/spec/unit/iiif/v3/presentation/choice_spec.rb b/spec/unit/iiif/v3/presentation/choice_spec.rb index 0f76f8e..48c91d1 100644 --- a/spec/unit/iiif/v3/presentation/choice_spec.rb +++ b/spec/unit/iiif/v3/presentation/choice_spec.rb @@ -1,119 +1,123 @@ describe IIIF::V3::Presentation::Choice do - - describe '#prohibited_keys' do - it 'contains the expected key names' do + describe "#prohibited_keys" do + it "contains the expected key names" do keys = described_class::PAGING_PROPERTIES + described_class::CONTENT_RESOURCE_PROPERTIES + - %w{ - nav_date - viewing_direction - start_canvas - content_annotations - } - expect(subject.prohibited_keys).to include(*keys) - end + %w[ + nav_date + viewing_direction + start_canvas + content_annotations + ] + expect(subject.prohibited_keys).to include(*keys) + end end - describe '#any_type_keys' do - it 'default' do - expect(subject.any_type_keys).to include('default') + describe "#any_type_keys" do + it "default" do + expect(subject.any_type_keys).to include("default") end end - describe '#string_only_keys' do - it 'choice_hint' do - expect(subject.string_only_keys).to include('choice_hint') + describe "#string_only_keys" do + it "choice_hint" do + expect(subject.string_only_keys).to include("choice_hint") end end - describe '#array_only_keys' do - it 'items' do - expect(subject.array_only_keys).to include('items') + describe "#array_only_keys" do + it "items" do + expect(subject.array_only_keys).to include("items") end end - describe '#legal_choice_hint_values' do - it 'contains the expected values' do - expect(subject.legal_choice_hint_values).to contain_exactly('client', 'user') + describe "#legal_choice_hint_values" do + it "contains the expected values" do + expect(subject.legal_choice_hint_values).to contain_exactly("client", "user") end end - describe '#legal_viewing_hint_values' do - it 'contains none' do - expect(subject.legal_viewing_hint_values).to contain_exactly('none') + describe "#legal_viewing_hint_values" do + it "contains none" do + expect(subject.legal_viewing_hint_values).to contain_exactly("none") end end - describe '#initialize' do - it 'sets type to Choice by default' do - expect(subject['type']).to eq 'Choice' + describe "#initialize" do + it "sets type to Choice by default" do + expect(subject["type"]).to eq "Choice" end - it 'allows subclasses to override type' do + it "allows subclasses to override type" do subclass = Class.new(described_class) do - def initialize(hsh={}) - hsh = { 'type' => 'a:SubClass' } - super(hsh) + def initialize(_hsh = {}) + super({"type" => "a:SubClass"}) end end sub = subclass.new - expect(sub['type']).to eq 'a:SubClass' + expect(sub["type"]).to eq "a:SubClass" end - it 'allows type to be passed in' do - my_choice = described_class.new('type' => 'bar') - expect(my_choice.type).to eq 'bar' + it "allows type to be passed in" do + my_choice = described_class.new("type" => "bar") + expect(my_choice.type).to eq "bar" end end - describe '#validate' do - it 'raises an IllegalValueError if choice_hint isn\'t an allowable value' do + describe "#validate" do + it "raises an IllegalValueError if choice_hint isn't an allowable value" do exp_err_msg = "choiceHint for #{described_class} must be one of [\"client\", \"user\"]." - subject['choice_hint'] = 'foo' + subject["choice_hint"] = "foo" expect { subject.validate }.to raise_error IIIF::V3::Presentation::IllegalValueError, exp_err_msg end end - describe 'realistic examples' do - describe 'from digerati' do - let(:item_type) { 'Video' } - let(:item1_id) { 'http://example.org/foo.mp4f' } - let(:item1_mime) { 'video/mp4' } - let(:item1_res) { IIIF::V3::Presentation::Resource.new( - 'id' => item1_id, - 'type' => item_type, - 'format' => item1_mime - )} - let(:item2_id) { 'http://example.org/foo.webm' } - let(:item2_mime) { 'video/webm' } - let(:item2_res) { IIIF::V3::Presentation::Resource.new( - 'id' => item2_id, - 'type' => item_type, - 'format' => item2_mime - )} - let(:choice) { IIIF::V3::Presentation::Choice.new( - 'choiceHint' => 'client', - 'items' => [item1_res, item2_res] - )} - it 'validates' do - expect{choice.validate}.not_to raise_error + describe "realistic examples" do + describe "from digerati" do + let(:item_type) { "Video" } + let(:item1_id) { "http://example.org/foo.mp4f" } + let(:item1_mime) { "video/mp4" } + let(:item1_res) { + IIIF::V3::Presentation::Resource.new( + "id" => item1_id, + "type" => item_type, + "format" => item1_mime + ) + } + let(:item2_id) { "http://example.org/foo.webm" } + let(:item2_mime) { "video/webm" } + let(:item2_res) { + IIIF::V3::Presentation::Resource.new( + "id" => item2_id, + "type" => item_type, + "format" => item2_mime + ) + } + let(:choice) { + IIIF::V3::Presentation::Choice.new( + "choiceHint" => "client", + "items" => [item1_res, item2_res] + ) + } + it "validates" do + expect { choice.validate }.not_to raise_error end - it 'has expected required values' do - expect(choice['type']).to eq 'Choice' + it "has expected required values" do + expect(choice["type"]).to eq "Choice" end - it 'has expected additional values' do + it "has expected additional values" do expect(choice.id).to be_nil - expect(choice['choice_hint']).to eq 'client' - expect(choice.choiceHint).to eq 'client' - expect(choice['items']).to eq [item1_res, item2_res] - first = choice['items'].first + expect(choice["choice_hint"]).to eq "client" + expect(choice.choiceHint).to eq "client" + expect(choice["items"]).to eq [item1_res, item2_res] + first = choice["items"].first expect(first.keys.size).to eq 3 - expect(first['id']).to eq item1_id - expect(first['type']).to eq item_type - expect(first['format']).to eq item1_mime - second = choice['items'].last + expect(first["id"]).to eq item1_id + expect(first["type"]).to eq item_type + expect(first["format"]).to eq item1_mime + second = choice["items"].last expect(second.keys.size).to eq 3 - expect(second['id']).to eq item2_id - expect(second['type']).to eq item_type - expect(second['format']).to eq item2_mime + expect(second["id"]).to eq item2_id + expect(second["type"]).to eq item_type + expect(second["format"]).to eq item2_mime end end end diff --git a/spec/unit/iiif/v3/presentation/collection_spec.rb b/spec/unit/iiif/v3/presentation/collection_spec.rb index 229418f..ccd0d56 100644 --- a/spec/unit/iiif/v3/presentation/collection_spec.rb +++ b/spec/unit/iiif/v3/presentation/collection_spec.rb @@ -1,55 +1,50 @@ describe IIIF::V3::Presentation::Collection do - let(:fixed_values) do { "@context" => [ "http://iiif.io/api/presentation/3/context.json", "http://www.w3.org/ns/anno.jsonld" ], - 'id' => 'http://example.org/iiif/collection/top', - 'type' => 'Collection', - 'label' => 'Top Level Collection for Example Organization', - 'description' => 'Description of Collection', - 'attribution' => 'Provided by Example Organization', - - 'collections' => [ - { 'id' => 'http://example.org/iiif/collection/part1', - 'type' => 'Collection', - 'label' => 'Sub Collection 1' - }, - { 'id' => 'http://example.org/iiif/collection/part2', - 'type' => 'Collection', - 'label' => 'Sub Collection 2' - } + "id" => "http://example.org/iiif/collection/top", + "type" => "Collection", + "label" => "Top Level Collection for Example Organization", + "description" => "Description of Collection", + "attribution" => "Provided by Example Organization", + + "collections" => [ + {"id" => "http://example.org/iiif/collection/part1", + "type" => "Collection", + "label" => "Sub Collection 1"}, + {"id" => "http://example.org/iiif/collection/part2", + "type" => "Collection", + "label" => "Sub Collection 2"} ], - 'manifests' => [ - { 'id' => 'http://example.org/iiif/book1/manifest', - 'type' => 'Manifest', - 'label' => 'Book 1' - } + "manifests" => [ + {"id" => "http://example.org/iiif/book1/manifest", + "type" => "Manifest", + "label" => "Book 1"} ] } end - describe '#initialize' do - it 'sets type to Collection by default' do - expect(subject['type']).to eq 'Collection' + describe "#initialize" do + it "sets type to Collection by default" do + expect(subject["type"]).to eq "Collection" end end describe "#{described_class}.define_methods_for_array_only_keys" do - it_behaves_like 'it has the appropriate methods for array-only keys v3' + it_behaves_like "it has the appropriate methods for array-only keys v3" end describe "#{described_class}.define_methods_for_string_only_keys" do - it_behaves_like 'it has the appropriate methods for string-only keys v3' + it_behaves_like "it has the appropriate methods for string-only keys v3" end describe "#{described_class}.define_methods_for_any_type_keys" do - it_behaves_like 'it has the appropriate methods for any-type keys v3' + it_behaves_like "it has the appropriate methods for any-type keys v3" end - describe '#validate' do + describe "#validate" do end - end diff --git a/spec/unit/iiif/v3/presentation/image_resource_spec.rb b/spec/unit/iiif/v3/presentation/image_resource_spec.rb index 161f755..f0b25bd 100644 --- a/spec/unit/iiif/v3/presentation/image_resource_spec.rb +++ b/spec/unit/iiif/v3/presentation/image_resource_spec.rb @@ -1,155 +1,154 @@ describe IIIF::V3::Presentation::ImageResource do - - describe '#initialize' do - it 'sets type to Image' do - expect(subject['type']).to eq 'Image' + describe "#initialize" do + it "sets type to Image" do + expect(subject["type"]).to eq "Image" end end - describe 'realistic examples' do - let(:img_id) { 'https://example.org/image/iiif/abc666' } + describe "realistic examples" do + let(:img_id) { "https://example.org/image/iiif/abc666" } let(:image_v2_service) { IIIF::V3::Presentation::Service.new( - '@context' => 'http://iiif.io/api/image/2/context.json', - '@id' => img_id, - 'id' => img_id, - 'profile' => 'http://iiif.io/api/image/2/level1.json' + "@context" => "http://iiif.io/api/image/2/context.json", + "@id" => img_id, + "id" => img_id, + "profile" => "http://iiif.io/api/image/2/level1.json" ) } - let(:img_mimetype) { 'image/jpeg' } + let(:img_mimetype) { "image/jpeg" } let(:width) { 999 } let(:height) { 666 } - describe 'stanford' do - describe 'thumbnail per purl code' do + describe "stanford" do + describe "thumbnail per purl code" do let(:thumb_id) { "#{img_id}/full/!400,400/0/default.jpg" } let(:thumb_object) { thumb = IIIF::V3::Presentation::ImageResource.new - thumb['type'] = 'Image' - thumb['id'] = thumb_id + thumb["type"] = "Image" + thumb["id"] = thumb_id thumb.format = img_mimetype thumb.service = [image_v2_service] thumb } - it 'validates' do - expect{thumb_object.validate}.not_to raise_error + it "validates" do + expect { thumb_object.validate }.not_to raise_error end - it 'has expected required values' do - expect(thumb_object.type).to eq 'Image' + it "has expected required values" do + expect(thumb_object.type).to eq "Image" expect(thumb_object.id).to eq thumb_id end - it 'has expected additional values' do + it "has expected additional values" do expect(thumb_object.format).to eq img_mimetype expect(thumb_object.service.first).to eq image_v2_service end end - describe 'full size per purl code' do + describe "full size per purl code" do let(:full_id) { "#{img_id}/full/full/0/default.jpg" } let(:image_object) { img = IIIF::V3::Presentation::ImageResource.new - img['id'] = full_id + img["id"] = full_id img.format = img_mimetype img.height = height img.width = width img.service = [image_v2_service] img } - describe 'world visible' do - it 'validates' do - expect{image_object.validate}.not_to raise_error + describe "world visible" do + it "validates" do + expect { image_object.validate }.not_to raise_error end - it 'has expected required values' do - expect(image_object.type).to eq 'Image' + it "has expected required values" do + expect(image_object.type).to eq "Image" expect(image_object.id).to eq full_id end - it 'has expected additional values' do + it "has expected additional values" do expect(image_object.format).to eq img_mimetype expect(image_object.height).to eq height expect(image_object.width).to eq width expect(image_object.service.first).to eq image_v2_service end - it 'has expected service value' do + it "has expected service value" do img_service_obj = image_object.service.first expect(img_service_obj.class).to eq IIIF::V3::Presentation::Service expect(img_service_obj.keys.size).to eq 4 expect(img_service_obj.id).to eq img_id - expect(img_service_obj['@id']).to eq img_id + expect(img_service_obj["@id"]).to eq img_id expect(img_service_obj.profile).to eq IIIF::V3::Presentation::Service::IIIF_IMAGE_V2_LEVEL1_PROFILE end end - describe 'requires login' do - let(:service_label) { 'login message' } - let(:token_service_id) { 'https://example.org/iiif/token' } + describe "requires login" do + let(:service_label) { "login message" } + let(:token_service_id) { "https://example.org/iiif/token" } let(:login_service) { IIIF::V3::Presentation::Service.new( - 'id' => 'https://example.org/auth/iiif', - 'profile' => 'http://iiif.io/api/auth/1/login', - 'label' => service_label, - 'service' => [{ - 'id' => token_service_id, - 'profile' => 'http://iiif.io/api/auth/1/token' + "id" => "https://example.org/auth/iiif", + "profile" => "http://iiif.io/api/auth/1/login", + "label" => service_label, + "service" => [{ + "id" => token_service_id, + "profile" => "http://iiif.io/api/auth/1/token" }] ) } let(:image_object_w_login) { img = image_object - img.service.first['service'] = [login_service] + img.service.first["service"] = [login_service] img } - it 'validates' do - expect{image_object_w_login.validate}.not_to raise_error + it "validates" do + expect { image_object_w_login.validate }.not_to raise_error end - it 'has expected service value' do + it "has expected service value" do img_service_obj = image_object_w_login.service.first expect(img_service_obj.class).to eq IIIF::V3::Presentation::Service expect(img_service_obj.keys.size).to eq 5 expect(img_service_obj.id).to eq img_id - expect(img_service_obj['@id']).to eq img_id + expect(img_service_obj["@id"]).to eq img_id expect(img_service_obj.profile).to eq IIIF::V3::Presentation::Service::IIIF_IMAGE_V2_LEVEL1_PROFILE expect(img_service_obj.service.class).to eq Array expect(img_service_obj.service.size).to eq 1 login_service_obj = img_service_obj.service.first expect(login_service_obj.keys.size).to eq 4 - expect(login_service.id).to eq 'https://example.org/auth/iiif' + expect(login_service.id).to eq "https://example.org/auth/iiif" expect(login_service.profile).to eq IIIF::V3::Presentation::Service::IIIF_AUTHENTICATION_V1_LOGIN_PROFILE expect(login_service.label).to eq service_label expect(login_service.service.class).to eq Array expect(login_service.service.size).to eq 1 token_service_obj = login_service_obj.service.first - expect(token_service_obj['id']).to eq token_service_id - expect(token_service_obj['profile']).to eq IIIF::V3::Presentation::Service::IIIF_AUTHENTICATION_V1_TOKEN_PROFILE + expect(token_service_obj["id"]).to eq token_service_id + expect(token_service_obj["profile"]).to eq IIIF::V3::Presentation::Service::IIIF_AUTHENTICATION_V1_TOKEN_PROFILE end end end end - describe 'image examples from http://prezi3.iiif.io/api/presentation/3.0' do + describe "image examples from http://prezi3.iiif.io/api/presentation/3.0" do let(:image_object) { IIIF::V3::Presentation::ImageResource.new({ - 'id' => "#{img_id}/full/full/0/default.jpg", - 'type' => 'dctypes:Image', - 'format' => img_mimetype, - 'height' => height, - 'width' => width, - 'service' => [image_v2_service] - }) + "id" => "#{img_id}/full/full/0/default.jpg", + "type" => "dctypes:Image", + "format" => img_mimetype, + "height" => height, + "width" => width, + "service" => [image_v2_service] + }) } - describe 'simpler' do - it 'validates' do - expect{image_object.validate}.not_to raise_error + describe "simpler" do + it "validates" do + expect { image_object.validate }.not_to raise_error end - it 'has expected required values' do + it "has expected required values" do expect(image_object.id).to eq "#{img_id}/full/full/0/default.jpg" - expect(image_object.type).to eq 'dctypes:Image' + expect(image_object.type).to eq "dctypes:Image" end - it 'has expected additional values' do + it "has expected additional values" do expect(image_object.format).to eq img_mimetype expect(image_object.height).to eq height expect(image_object.width).to eq width expect(image_object.service.first).to eq image_v2_service end end - describe 'height and width in service' do + describe "height and width in service" do # { # "id": "http://example.org/images/book1-page2/full/1500,2000/0/default.jpg", # "type": "dctypes:Image", @@ -167,21 +166,21 @@ # } let(:img_obj) { img = image_object - img.service.first['height'] = 6666 - img.service.first['width'] = 9999 - img.service.first['tiles'] = [{"width" => 512, "scaleFactors" => [1,2,4,8,16]}] + img.service.first["height"] = 6666 + img.service.first["width"] = 9999 + img.service.first["tiles"] = [{"width" => 512, "scaleFactors" => [1, 2, 4, 8, 16]}] img } - it 'validates' do - expect{img_obj.validate}.not_to raise_error + it "validates" do + expect { img_obj.validate }.not_to raise_error end - it 'has expected service value' do + it "has expected service value" do service_obj = img_obj.service.first expect(service_obj.class).to eq IIIF::V3::Presentation::Service expect(service_obj.keys.size).to eq 7 - expect(service_obj['height']).to eq 6666 - expect(service_obj['width']).to eq 9999 - expect(service_obj['tiles']).to eq [{"width" => 512, "scaleFactors" => [1,2,4,8,16]}] + expect(service_obj["height"]).to eq 6666 + expect(service_obj["width"]).to eq 9999 + expect(service_obj["tiles"]).to eq [{"width" => 512, "scaleFactors" => [1, 2, 4, 8, 16]}] end end end diff --git a/spec/unit/iiif/v3/presentation/manifest_spec.rb b/spec/unit/iiif/v3/presentation/manifest_spec.rb index 4d9ec7c..57cab24 100644 --- a/spec/unit/iiif/v3/presentation/manifest_spec.rb +++ b/spec/unit/iiif/v3/presentation/manifest_spec.rb @@ -1,244 +1,254 @@ describe IIIF::V3::Presentation::Manifest do - - describe '#required_keys' do + describe "#required_keys" do # NOTE: relaxing requirement for items as Universal Viewer currently only accepts sequences # see https://github.com/sul-dlss/osullivan/issues/27, sul-dlss/purl/issues/167 # %w{ type id label items }.each do |k| - %w{ type id label }.each do |k| + %w[type id label].each do |k| it k do expect(subject.required_keys).to include(k) end end end - describe '#prohibited_keys' do - it 'contains the expected key names' do + describe "#prohibited_keys" do + it "contains the expected key names" do keys = described_class::CONTENT_RESOURCE_PROPERTIES + described_class::PAGING_PROPERTIES + - %w{ + %w[ start_canvas content_annotation - } + ] expect(subject.prohibited_keys).to include(*keys) end end - describe '#uri_only_keys' do - it 'id' do - expect(subject.uri_only_keys).to include('id') + describe "#uri_only_keys" do + it "id" do + expect(subject.uri_only_keys).to include("id") end end - describe '#array_only_keys' do + describe "#array_only_keys" do # NOTE: also allowing sequences as Universal Viewer currently only accepts sequences # see https://github.com/sul-dlss/osullivan/issues/27, sul-dlss/purl/issues/167 - %w{ items sequences structures}.each do |k| + %w[items sequences structures].each do |k| it k do expect(subject.array_only_keys).to include(k) end end end - describe '#legal_viewing_hint_values' do - it 'contains the expected values' do - expect(subject.legal_viewing_hint_values).to contain_exactly('individuals', 'paged', 'continuous', 'auto-advance') + describe "#legal_viewing_hint_values" do + it "contains the expected values" do + expect(subject.legal_viewing_hint_values).to contain_exactly("individuals", "paged", "continuous", "auto-advance") end end - describe '#initialize' do - it 'sets type to Manifest by default' do - expect(subject['type']).to eq 'Manifest' + describe "#initialize" do + it "sets type to Manifest by default" do + expect(subject["type"]).to eq "Manifest" end - it 'allows subclasses to override type' do + it "allows subclasses to override type" do subclass = Class.new(described_class) do - def initialize(hsh={}) - hsh = { 'type' => 'a:SubClass' } - super(hsh) + def initialize(_hsh = {}) + super({"type" => "a:SubClass"}) end end sub = subclass.new - expect(sub['type']).to eq 'a:SubClass' + expect(sub["type"]).to eq "a:SubClass" end end - let(:manifest_id) { 'http://www.example.org/iiif/book1/manifest' } + let(:manifest_id) { "http://www.example.org/iiif/book1/manifest" } - describe '#validate' do - it 'raises an IllegalValueError if id is not http' do - subject.label = {'en' => ['Book 1']} - subject['id'] = 'ftp://www.example.org' - subject['items'] = [IIIF::V3::Presentation::Sequence.new] + describe "#validate" do + it "raises an IllegalValueError if id is not http" do + subject.label = {"en" => ["Book 1"]} + subject["id"] = "ftp://www.example.org" + subject["items"] = [IIIF::V3::Presentation::Sequence.new] exp_err_msg = "id must be an http(s) URI for #{described_class}" expect { subject.validate }.to raise_error(IIIF::V3::Presentation::IllegalValueError, exp_err_msg) end - let(:item_list_err) { 'The items list must have at least one entry (and it must be a IIIF::V3::Presentation::Canvas)' } - let(:item_entry_err) { 'All entries in the items list must be a IIIF::V3::Presentation::Canvas' } + let(:item_list_err) { "The items list must have at least one entry (and it must be a IIIF::V3::Presentation::Canvas)" } + let(:item_entry_err) { "All entries in the items list must be a IIIF::V3::Presentation::Canvas" } - it 'raises MissingRequiredKeyError if no items or sequences key' do - subject['id'] = manifest_id - subject.label = {'en' => ['Book 1']} + it "raises MissingRequiredKeyError if no items or sequences key" do + subject["id"] = manifest_id + subject.label = {"en" => ["Book 1"]} expect { subject.validate }.to raise_error(IIIF::V3::Presentation::MissingRequiredKeyError, item_list_err) end - describe 'items' do - it 'raises MissingRequiredKeyError for items entry without values' do - subject['id'] = manifest_id - subject.label = {'en' => ['Book 1']} - subject['items'] = [] + describe "items" do + it "raises MissingRequiredKeyError for items entry without values" do + subject["id"] = manifest_id + subject.label = {"en" => ["Book 1"]} + subject["items"] = [] expect { subject.validate }.to raise_error(IIIF::V3::Presentation::MissingRequiredKeyError, item_list_err) end - it 'raises IllegalValueError for items entry that is not a Sequence' do - subject['id'] = manifest_id - subject.label = {'en' => ['Book 1']} - subject['items'] = [IIIF::V3::Presentation::Sequence.new, IIIF::V3::Presentation::Canvas.new] + it "raises IllegalValueError for items entry that is not a Sequence" do + subject["id"] = manifest_id + subject.label = {"en" => ["Book 1"]} + subject["items"] = [IIIF::V3::Presentation::Sequence.new, IIIF::V3::Presentation::Canvas.new] expect { subject.validate }.to raise_error(IIIF::V3::Presentation::IllegalValueError, item_entry_err) end - it 'raises no error items populated with canvases' do - subject['items'] = [IIIF::V3::Presentation::Canvas.new] - subject['id'] = manifest_id - subject.label = {'en' => ['Book 1']} + it "raises no error items populated with canvases" do + subject["items"] = [IIIF::V3::Presentation::Canvas.new] + subject["id"] = manifest_id + subject.label = {"en" => ["Book 1"]} expect { subject.validate }.not_to raise_error end end - it 'raises IllegalValueError for structures entry that is not a Range' do - subject['id'] = manifest_id - subject.label = {'en' => ['Book 1']} - subject['items'] = [IIIF::V3::Presentation::Canvas.new] - subject['structures'] = [IIIF::V3::Presentation::Sequence.new] + it "raises IllegalValueError for structures entry that is not a Range" do + subject["id"] = manifest_id + subject.label = {"en" => ["Book 1"]} + subject["items"] = [IIIF::V3::Presentation::Canvas.new] + subject["structures"] = [IIIF::V3::Presentation::Sequence.new] exp_err_msg = "All entries in the structures list must be a IIIF::V3::Presentation::Range" expect { subject.validate }.to raise_error(IIIF::V3::Presentation::IllegalValueError, exp_err_msg) end - it 'raises no error when structures entry is a Range' do - subject['id'] = manifest_id - subject.label = {'en' => ['Book 1']} - subject['items'] = [IIIF::V3::Presentation::Canvas.new] - subject['structures'] = [IIIF::V3::Presentation::Range.new] + it "raises no error when structures entry is a Range" do + subject["id"] = manifest_id + subject.label = {"en" => ["Book 1"]} + subject["items"] = [IIIF::V3::Presentation::Canvas.new] + subject["structures"] = [IIIF::V3::Presentation::Range.new] expect { subject.validate }.not_to raise_error end end - describe 'realistic examples' do - let!(:canvas_object) { IIIF::V3::Presentation::Canvas.new({ - "id" => "https://example.org/abc666/iiif3/canvas/0001", - "label" => {'en' => ['image']}, - "height" => 7579, - "width" => 10108, - "content" => [] - })} - describe 'realistic(?) minimal manifest' do - let!(:manifest_object) { described_class.new({ - "@context" => [ - "http://www.w3.org/ns/anno.jsonld", - "http://iiif.io/api/presentation/3/context.json" - ], - "id" => "https://example.org/abc666/iiif3/manifest", - "label" => {"en" => ["blah"]}, - "requiredStatement" => { - "label": { "en": [ "Attribution" ] }, - "value": { "en": [ "bleah" ] }, - }, - 'summary' => { 'en' => ['blargh'] }, - "items" => [canvas_object] - })} - it 'validates' do - expect{manifest_object.validate}.not_to raise_error + describe "realistic examples" do + let!(:canvas_object) { + IIIF::V3::Presentation::Canvas.new({ + "id" => "https://example.org/abc666/iiif3/canvas/0001", + "label" => {"en" => ["image"]}, + "height" => 7579, + "width" => 10108, + "content" => [] + }) + } + describe "realistic(?) minimal manifest" do + let!(:manifest_object) { + described_class.new({ + "@context" => [ + "http://www.w3.org/ns/anno.jsonld", + "http://iiif.io/api/presentation/3/context.json" + ], + "id" => "https://example.org/abc666/iiif3/manifest", + "label" => {"en" => ["blah"]}, + "requiredStatement" => { + label: {en: ["Attribution"]}, + value: {en: ["bleah"]} + }, + "summary" => {"en" => ["blargh"]}, + "items" => [canvas_object] + }) + } + it "validates" do + expect { manifest_object.validate }.not_to raise_error end - it 'has expected required values' do - expect(manifest_object.type).to eq 'Manifest' + it "has expected required values" do + expect(manifest_object.type).to eq "Manifest" expect(manifest_object.id).to eq "https://example.org/abc666/iiif3/manifest" - expect(manifest_object.label['en']).to include "blah" + expect(manifest_object.label["en"]).to include "blah" expect(manifest_object.items.size).to be 1 expect(manifest_object.items.first).to eq canvas_object end - it 'has expected context' do - expect(manifest_object['@context'].size).to be 2 - expect(manifest_object['@context']).to include(*IIIF::V3::Presentation::CONTEXT) + it "has expected context" do + expect(manifest_object["@context"].size).to be 2 + expect(manifest_object["@context"]).to include(*IIIF::V3::Presentation::CONTEXT) end - it 'has other values' do - expect(manifest_object['required_statement'][:value][:en].first).to eq 'bleah' - expect(manifest_object.summary['en'].first).to eq 'blargh' + it "has other values" do + expect(manifest_object["required_statement"][:value][:en].first).to eq "bleah" + expect(manifest_object.summary["en"].first).to eq "blargh" end end - describe 'realistic example from Stanford purl manifests' do - let!(:logo_service) { IIIF::V3::Presentation::Service.new({ - "@id" => "https://example.org/logo", - "@type" => "ImageService2", - "id" => "https://example.org/logo", - "profile" => "http://iiif.io/api/image/2/level1.json" - })} - let!(:thumbnail_image_service) { IIIF::V3::Presentation::Service.new({ - "@id" => "https://example.org/image/iiif/abc666_05_0001", - "id" => "https://example.org/image/iiif/abc666_05_0001", - "profile" => IIIF::V3::Presentation::Service::IIIF_IMAGE_V2_LEVEL1_PROFILE - })} - let!(:thumbnail_image) { IIIF::V3::Presentation::ImageResource.new({ - "id" => "https://example.org/image/iiif/abc666_05_0001/full/!400,400/0/default.jpg", - "format" => "image/jpeg", - "service" => [thumbnail_image_service] - })} - let!(:manifest_object) { described_class.new({ - "id" => "https://example.org/abc666/iiif3/manifest", - "label" => {"en" => ["blah"]}, - "requiredStatement" => { - "label": { "en": [ "Attribution" ] }, - "value": { "en": [ "bleah" ] }, - }, - 'summary' => { 'en' => ['blargh'] }, - "items" => [canvas_object], - "logo" => { - "id" => "https://example.org/logo/full/400,/0/default.jpg", - "service" => [logo_service] - }, - "seeAlso" => { - "id" => "https://example.org/abc666.mods", - "format" => "application/mods+xml" - }, - "viewingHint" => "paged", - "viewingDirection" => "right-to-left", - "metadata" => [ - { - "label" => "Type", - "value" => "map" + describe "realistic example from Stanford purl manifests" do + let!(:logo_service) { + IIIF::V3::Presentation::Service.new({ + "@id" => "https://example.org/logo", + "@type" => "ImageService2", + "id" => "https://example.org/logo", + "profile" => "http://iiif.io/api/image/2/level1.json" + }) + } + let!(:thumbnail_image_service) { + IIIF::V3::Presentation::Service.new({ + "@id" => "https://example.org/image/iiif/abc666_05_0001", + "id" => "https://example.org/image/iiif/abc666_05_0001", + "profile" => IIIF::V3::Presentation::Service::IIIF_IMAGE_V2_LEVEL1_PROFILE + }) + } + let!(:thumbnail_image) { + IIIF::V3::Presentation::ImageResource.new({ + "id" => "https://example.org/image/iiif/abc666_05_0001/full/!400,400/0/default.jpg", + "format" => "image/jpeg", + "service" => [thumbnail_image_service] + }) + } + let!(:manifest_object) { + described_class.new({ + "id" => "https://example.org/abc666/iiif3/manifest", + "label" => {"en" => ["blah"]}, + "requiredStatement" => { + label: {en: ["Attribution"]}, + value: {en: ["bleah"]} }, - { - "label" => "Rights", - "value" => "stuff" - } + "summary" => {"en" => ["blargh"]}, + "items" => [canvas_object], + "logo" => { + "id" => "https://example.org/logo/full/400,/0/default.jpg", + "service" => [logo_service] + }, + "seeAlso" => { + "id" => "https://example.org/abc666.mods", + "format" => "application/mods+xml" + }, + "viewingHint" => "paged", + "viewingDirection" => "right-to-left", + "metadata" => [ + { + "label" => "Type", + "value" => "map" + }, + { + "label" => "Rights", + "value" => "stuff" + } ], - "thumbnail" => [thumbnail_image] - })} - it 'thumbnail image object validates' do - expect{thumbnail_image.validate}.not_to raise_error + "thumbnail" => [thumbnail_image] + }) + } + it "thumbnail image object validates" do + expect { thumbnail_image.validate }.not_to raise_error end - it 'manifest validates' do - expect{manifest_object.validate}.not_to raise_error + it "manifest validates" do + expect { manifest_object.validate }.not_to raise_error end - it 'has expected required values' do - expect(manifest_object.type).to eq 'Manifest' + it "has expected required values" do + expect(manifest_object.type).to eq "Manifest" expect(manifest_object.id).to eq "https://example.org/abc666/iiif3/manifest" - expect(manifest_object.label['en']).to include "blah" + expect(manifest_object.label["en"]).to include "blah" expect(manifest_object.items.size).to be 1 expect(manifest_object.items.first).to eq canvas_object end - it 'has expected additional content' do - expect(manifest_object['required_statement'][:value][:en].first).to eq 'bleah' - expect(manifest_object.summary['en'].first).to eq 'blargh' + it "has expected additional content" do + expect(manifest_object["required_statement"][:value][:en].first).to eq "bleah" + expect(manifest_object.summary["en"].first).to eq "blargh" expect(manifest_object.logo.keys.size).to be 2 expect(manifest_object.seeAlso.keys.size).to be 2 expect(manifest_object.metadata.size).to be 2 expect(manifest_object.thumbnail.size).to be 1 end - describe 'from stanford purl CODE' do + describe "from stanford purl CODE" do let!(:manifest_data) { { "id" => "https://example.org/abc666/iiif3/manifest", "label" => {"en" => ["blah"]}, "requiredStatement" => { - "label": { "en": [ "Attribution" ] }, - "value": { "en": [ "bleah" ] }, + label: {en: ["Attribution"]}, + value: {en: ["bleah"]} }, "logo" => { "id" => "https://example.org/logo/full/400,/0/default.jpg", @@ -252,29 +262,29 @@ def initialize(hsh={}) } let!(:manifest_object) { m = described_class.new manifest_data - m.viewingHint = 'paged' + m.viewingHint = "paged" m.metadata = [ - { 'label' => 'title', 'value' => 'who wants to know?' }, - { 'label' => 'PublishDate', 'value' => 'sometime' } + {"label" => "title", "value" => "who wants to know?"}, + {"label" => "PublishDate", "value" => "sometime"} ] - m.summary = { 'en' => ['blargh'] } + m.summary = {"en" => ["blargh"]} m.thumbnail = [thumbnail_image] m.items << canvas_object m } - it 'manifest validates' do - expect{manifest_object.validate}.not_to raise_error + it "manifest validates" do + expect { manifest_object.validate }.not_to raise_error end - it 'has expected required values' do - expect(manifest_object.type).to eq 'Manifest' + it "has expected required values" do + expect(manifest_object.type).to eq "Manifest" expect(manifest_object.id).to eq "https://example.org/abc666/iiif3/manifest" - expect(manifest_object.label['en']).to include "blah" + expect(manifest_object.label["en"]).to include "blah" expect(manifest_object.items.size).to be 1 expect(manifest_object.items.first).to eq canvas_object end - it 'has expected additional content' do - expect(manifest_object['required_statement'][:value][:en].first).to eq 'bleah' - expect(manifest_object.summary['en'].first).to eq 'blargh' + it "has expected additional content" do + expect(manifest_object["required_statement"][:value][:en].first).to eq "bleah" + expect(manifest_object.summary["en"].first).to eq "blargh" expect(manifest_object.logo.keys.size).to be 2 expect(manifest_object.seeAlso.keys.size).to be 2 expect(manifest_object.metadata.size).to be 2 @@ -282,86 +292,89 @@ def initialize(hsh={}) end end end - describe 'example from http://prezi3.iiif.io/api/presentation/3.0' do - let!(:range_object) { IIIF::V3::Presentation::Range.new({ - "id" => "http://example.org/iiif/book1/range/top", - "label" => {"en" => ["home, home on the"]}, - "viewingHint" => ["top"] + describe "example from http://prezi3.iiif.io/api/presentation/3.0" do + let!(:range_object) { + IIIF::V3::Presentation::Range.new({ + "id" => "http://example.org/iiif/book1/range/top", + "label" => {"en" => ["home, home on the"]}, + "viewingHint" => ["top"] }) } - let!(:manifest_object) { described_class.new({ - "@context" => [ - "http://www.w3.org/ns/anno.jsonld", - "http://iiif.io/api/presentation/3/context.json" + let!(:manifest_object) { + described_class.new({ + "@context" => [ + "http://www.w3.org/ns/anno.jsonld", + "http://iiif.io/api/presentation/3/context.json" + ], + "id" => "http://example.org/iiif/book1/manifest", + "label" => {"en" => ["Book 1"]}, + "metadata" => [ + {"label" => {"en" => ["Author"]}, + "value" => {"@none" => ["Anne Author"]}}, + {"label" => {"en" => ["Published"]}, + "value" => { + "en" => ["Paris, circa 1400"], + "fr" => ["Paris, environ 1400"] + }}, + {"label" => {"en" => ["Notes"]}, + "value" => {"en" => ["Text of note 1", "Text of note 2"]}}, + {"label" => {"en" => ["Source"]}, + "value" => {"@none" => ["From: Some Collection"]}} ], - "id" => "http://example.org/iiif/book1/manifest", - "label" => {"en" => ["Book 1"]}, - "metadata" => [ - {"label" => {"en" => ["Author"]}, - "value" => {"@none" => ["Anne Author"]}}, - {"label" => {"en" => ["Published"]}, - "value" => { - "en" => ["Paris, circa 1400"], - "fr" => ["Paris, environ 1400"]} + "summary" => {"en" => ["A longer description of this example book. It should give some real information."]}, + "thumbnail" => [{ + "id" => "http://example.org/images/book1-page1/full/80,100/0/default.jpg", + "type" => "Image", + "service" => { + "id" => "http://example.org/images/book1-page1", + "type" => "ImageService2", + "profile" => ["http://iiif.io/api/image/2/level1.json"] + } + }], + "viewingDirection" => "right-to-left", + "viewingHint" => ["paged"], + "navDate" => "1856-01-01T00:00:00Z", + "rights" => "http://example.org/license.html", + "requiredStatement" => { + label: {en: ["Attribution"]}, + value: {en: ["bleah"]} }, - {"label" => {"en" => ["Notes"]}, - "value" => {"en" => ["Text of note 1", "Text of note 2"]}}, - {"label" => {"en" => ["Source"]}, - "value" => {"@none" => ["From: Some Collection"]}} - ], - "summary" => {"en" => ["A longer description of this example book. It should give some real information."]}, - "thumbnail" => [{ - "id" => "http://example.org/images/book1-page1/full/80,100/0/default.jpg", - "type" => "Image", - "service" => { - "id" => "http://example.org/images/book1-page1", - "type" => "ImageService2", - "profile" => ["http://iiif.io/api/image/2/level1.json"] - } - }], - "viewingDirection" => "right-to-left", - "viewingHint" => ["paged"], - "navDate" => "1856-01-01T00:00:00Z", - "rights" => "http://example.org/license.html", - "requiredStatement" => { - "label": { "en": [ "Attribution" ] }, - "value": { "en": [ "bleah" ] }, - }, - "logo" => { - "id" => "http://example.org/logos/institution1.jpg", - "service" => { + "logo" => { + "id" => "http://example.org/logos/institution1.jpg", + "service" => { "id" => "http://example.org/service/inst1", "type" => "ImageService2", "profile" => ["http://iiif.io/api/image/2/profiles/level2.json"] - } - }, - "related" => [{ - "id" => "http://example.org/videos/video-book1.mpg", - "format" => "video/mpeg" - }], - "service" => [{ - "id" => "http://example.org/service/example", - "profile" => ["http://example.org/docs/example-service.html"] - }], - "seeAlso" => [{ - "id" => "http://example.org/library/catalog/book1.xml", - "format" => "text/xml", - "profile" => ["http://example.org/profiles/bibliographic"] - }], - "rendering" => [{ - "id" => "http://example.org/iiif/book1.pdf", - "label" => {"en" => ["Download as PDF"]}, - "format" => "application/pdf" - }], - "within" => [{ - "id" => "http://example.org/collections/books/", - "type" => "Collection" - }], - "items" => [canvas_object], - "structures" => [range_object] - })} - it 'validates' do - expect{manifest_object.validate}.not_to raise_error + } + }, + "related" => [{ + "id" => "http://example.org/videos/video-book1.mpg", + "format" => "video/mpeg" + }], + "service" => [{ + "id" => "http://example.org/service/example", + "profile" => ["http://example.org/docs/example-service.html"] + }], + "seeAlso" => [{ + "id" => "http://example.org/library/catalog/book1.xml", + "format" => "text/xml", + "profile" => ["http://example.org/profiles/bibliographic"] + }], + "rendering" => [{ + "id" => "http://example.org/iiif/book1.pdf", + "label" => {"en" => ["Download as PDF"]}, + "format" => "application/pdf" + }], + "within" => [{ + "id" => "http://example.org/collections/books/", + "type" => "Collection" + }], + "items" => [canvas_object], + "structures" => [range_object] + }) + } + it "validates" do + expect { manifest_object.validate }.not_to raise_error end end end diff --git a/spec/unit/iiif/v3/presentation/nav_place_spec.rb b/spec/unit/iiif/v3/presentation/nav_place_spec.rb index e4e2f68..51f9196 100644 --- a/spec/unit/iiif/v3/presentation/nav_place_spec.rb +++ b/spec/unit/iiif/v3/presentation/nav_place_spec.rb @@ -2,117 +2,115 @@ let(:subject) { described_class.new(coordinate_texts: coordinate_texts, base_uri: base_uri) } let(:base_uri) { "https://purl.stanford.edu" } let(:invalid_coordinates) { ["bogus", "stuff", "is", "here"] } - let(:out_of_range_coordinates) { ['W 008°00′00″--W 004°00′00″/N 059°00′00″--N 543°00′00″'] } + let(:out_of_range_coordinates) { ["W 008°00′00″--W 004°00′00″/N 059°00′00″--N 543°00′00″"] } let(:wrong_axis_hemisphere_coordinates) { ["(W 117°57'--W 117°39'/E 34°50'--E 32°48')."] } let(:valid_coordinates) do ["W 23°54'00\"--E 53°36'00\"/N 71°19'00\"--N 33°30'00\"", - 'E 103°48ʹ/S 3°46ʹ).', - 'X 103°48ʹ/Y 3°46ʹ).', - 'In decimal degrees: (E 138.0--W 074.0/N 073.0--N 041.2).', - '23°54′00″W -- 53°36′00″E / 71°19′00″N -- 33°30′00″N' - ] + "E 103°48ʹ/S 3°46ʹ).", + "X 103°48ʹ/Y 3°46ʹ).", + "In decimal degrees: (E 138.0--W 074.0/N 073.0--N 041.2).", + "23°54′00″W -- 53°36′00″E / 71°19′00″N -- 33°30′00″N"] end let(:nav_place) do - { id: 'https://purl.stanford.edu/feature-collection/1', - type: 'FeatureCollection', - features: [{ id: 'https://purl.stanford.edu/iiif/feature/1', - type: 'Feature', - properties: {}, - geometry: { type: 'Polygon', - coordinates: [[[-23.9, 33.5], - [53.6, 33.5], - [53.6, 71.316667], - [-23.9, 71.316667], - [-23.9, 33.5]]] } }, - { id: 'https://purl.stanford.edu/iiif/feature/2', - type: 'Feature', - properties: {}, - geometry: { type: 'Point', coordinates: [103.8, -3.766667] } }, - { id: 'https://purl.stanford.edu/iiif/feature/3', - type: 'Feature', - properties: {}, - geometry: { coordinates: [103.8, 3.766667], type: "Point" } }, - { id: 'https://purl.stanford.edu/iiif/feature/4', - type: 'Feature', - properties: {}, - geometry: { type: 'MultiPolygon', - coordinates: [[[[138.0, 41.2], - [180.0, 41.2], - [180.0, 73.0], - [138.0, 73.0], - [138.0, 41.2]]], - [[[-180.0, 41.2], - [-74.0, 41.2], - [-74.0, 73.0], - [-180.0, 73.0], - [-180.0, 41.2]]]] } }, - { id: 'https://purl.stanford.edu/iiif/feature/5', - type: 'Feature', - properties: {}, - geometry: { type: 'Polygon', - coordinates: [[[-23.9, 33.5], - [53.6, 33.5], - [53.6, 71.316667], - [-23.9, 71.316667], - [-23.9, 33.5]]] } } - ] } + {id: "https://purl.stanford.edu/feature-collection/1", + type: "FeatureCollection", + features: [{id: "https://purl.stanford.edu/iiif/feature/1", + type: "Feature", + properties: {}, + geometry: {type: "Polygon", + coordinates: [[[-23.9, 33.5], + [53.6, 33.5], + [53.6, 71.316667], + [-23.9, 71.316667], + [-23.9, 33.5]]]}}, + {id: "https://purl.stanford.edu/iiif/feature/2", + type: "Feature", + properties: {}, + geometry: {type: "Point", coordinates: [103.8, -3.766667]}}, + {id: "https://purl.stanford.edu/iiif/feature/3", + type: "Feature", + properties: {}, + geometry: {coordinates: [103.8, 3.766667], type: "Point"}}, + {id: "https://purl.stanford.edu/iiif/feature/4", + type: "Feature", + properties: {}, + geometry: {type: "MultiPolygon", + coordinates: [[[[138.0, 41.2], + [180.0, 41.2], + [180.0, 73.0], + [138.0, 73.0], + [138.0, 41.2]]], + [[[-180.0, 41.2], + [-74.0, 41.2], + [-74.0, 73.0], + [-180.0, 73.0], + [-180.0, 41.2]]]]}}, + {id: "https://purl.stanford.edu/iiif/feature/5", + type: "Feature", + properties: {}, + geometry: {type: "Polygon", + coordinates: [[[-23.9, 33.5], + [53.6, 33.5], + [53.6, 71.316667], + [-23.9, 71.316667], + [-23.9, 33.5]]]}}]} end let(:nav_place_without_ids) do - without_id = ->(resource) { resource.reject { |key, _| key == :id } } - without_id.(nav_place).merge(features: nav_place[:features].map(&without_id)) + without_id = ->(resource) { resource.except(:id) } + without_id.call(nav_place).merge(features: nav_place[:features].map(&without_id)) end - describe '#initialize' do + describe "#initialize" do let(:coordinate_texts) { valid_coordinates } - ['', ' ', '/path', 'example.com', 'ftp://my.server'].each do |value| + ["", " ", "/path", "example.com", "ftp://my.server"].each do |value| context "when base_uri is #{value.inspect}" do let(:base_uri) { value } - it 'raises ArgumentError' do + it "raises ArgumentError" do expect { subject }.to raise_error(ArgumentError, /base_uri must be an absolute HTTP\(S\) URI/) end end end end - describe '#build' do - context 'when coordinates are valid' do + describe "#build" do + context "when coordinates are valid" do let(:coordinate_texts) { valid_coordinates } # Compare as JSON: Ruby's == treats a BigDecimal as equal to a Float, but # a BigDecimal serializes as a string, which GeoJSON does not allow. - it 'returns navPlace' do + it "returns navPlace" do expect(JSON.parse(subject.build.to_json)).to eq JSON.parse(nav_place.to_json) end - context 'without a base_uri' do + context "without a base_uri" do let(:subject) { described_class.new(coordinate_texts: coordinate_texts) } - it 'leaves out the ids' do + it "leaves out the ids" do expect(JSON.parse(subject.build.to_json)).to eq JSON.parse(nav_place_without_ids.to_json) end end end - context 'when the north and south edges are given in the reverse order' do + context "when the north and south edges are given in the reverse order" do let(:coordinate_texts) { ["W 10°00ʹ--E 20°00ʹ/S 5°00ʹ--N 5°00ʹ"] } - it 'still runs the ring counterclockwise' do - expect(JSON.parse(subject.build.to_json)['features'][0]['geometry']).to eq( - 'type' => 'Polygon', - 'coordinates' => [[[-10.0, -5.0], [20.0, -5.0], [20.0, 5.0], [-10.0, 5.0], [-10.0, -5.0]]] + it "still runs the ring counterclockwise" do + expect(JSON.parse(subject.build.to_json)["features"][0]["geometry"]).to eq( + "type" => "Polygon", + "coordinates" => [[[-10.0, -5.0], [20.0, -5.0], [20.0, 5.0], [-10.0, 5.0], [-10.0, -5.0]]] ) end end - context 'when a box crosses the antimeridian' do + context "when a box crosses the antimeridian" do let(:coordinate_texts) { ["E 170°00ʹ--W 170°00ʹ/N 10°00ʹ--S 10°00ʹ"] } - it 'splits it into a MultiPolygon, per the spec' do - expect(JSON.parse(subject.build.to_json)['features'][0]['geometry']).to eq( - 'type' => 'MultiPolygon', - 'coordinates' => [ + it "splits it into a MultiPolygon, per the spec" do + expect(JSON.parse(subject.build.to_json)["features"][0]["geometry"]).to eq( + "type" => "MultiPolygon", + "coordinates" => [ [[[170.0, -10.0], [180.0, -10.0], [180.0, 10.0], [170.0, 10.0], [170.0, -10.0]]], [[[-180.0, -10.0], [-170.0, -10.0], [-170.0, 10.0], [-180.0, 10.0], [-180.0, -10.0]]] ] @@ -120,177 +118,177 @@ end end - context 'when a box has an edge on the antimeridian' do + context "when a box has an edge on the antimeridian" do let(:coordinate_texts) { ["E 170°00ʹ--W 180°00ʹ/N 10°00ʹ--S 10°00ʹ", "E 180°00ʹ--W 170°00ʹ/N 10°00ʹ--S 10°00ʹ"] } - it 'makes bounds that do not require splitting' do - geometries = JSON.parse(subject.build.to_json)['features'].map { |feature| feature['geometry'] } + it "makes bounds that do not require splitting" do + geometries = JSON.parse(subject.build.to_json)["features"].map { |feature| feature["geometry"] } expect(geometries).to eq [ - { 'type' => 'Polygon', 'coordinates' => [[[170.0, -10.0], [180.0, -10.0], [180.0, 10.0], [170.0, 10.0], [170.0, -10.0]]] }, - { 'type' => 'Polygon', 'coordinates' => [[[-180.0, -10.0], [-170.0, -10.0], [-170.0, 10.0], [-180.0, 10.0], [-180.0, -10.0]]] } + {"type" => "Polygon", "coordinates" => [[[170.0, -10.0], [180.0, -10.0], [180.0, 10.0], [170.0, 10.0], [170.0, -10.0]]]}, + {"type" => "Polygon", "coordinates" => [[[-180.0, -10.0], [-170.0, -10.0], [-170.0, 10.0], [-180.0, 10.0], [-180.0, -10.0]]]} ] end end - context 'with decimal degrees' do - let(:coordinate_texts) { ['E 138.5°/N 35.25°'] } + context "with decimal degrees" do + let(:coordinate_texts) { ["E 138.5°/N 35.25°"] } - it 'reads the whole number' do - expect(JSON.parse(subject.build.to_json)['features'][0]['geometry']).to eq( - 'type' => 'Point', 'coordinates' => [138.5, 35.25] + it "reads the whole number" do + expect(JSON.parse(subject.build.to_json)["features"][0]["geometry"]).to eq( + "type" => "Point", "coordinates" => [138.5, 35.25] ) end end - context 'with decimal degrees and minutes and seconds' do - let(:coordinate_texts) { ['W 122°15.5ʹ/N 37°26ʹ30.5″'] } + context "with decimal degrees and minutes and seconds" do + let(:coordinate_texts) { ["W 122°15.5ʹ/N 37°26ʹ30.5″"] } - it 'keeps them' do - expect(JSON.parse(subject.build.to_json)['features'][0]['geometry']).to eq( - 'type' => 'Point', 'coordinates' => [-122.258333, 37.441806] + it "keeps them" do + expect(JSON.parse(subject.build.to_json)["features"][0]["geometry"]).to eq( + "type" => "Point", "coordinates" => [-122.258333, 37.441806] ) end end - context 'when coordinates are not present' do + context "when coordinates are not present" do let(:coordinate_texts) { [] } - it 'raises ArgumentError' do + it "raises ArgumentError" do expect { subject.build }.to raise_error(ArgumentError) end end - context 'when coordinates are invalid' do + context "when coordinates are invalid" do let(:coordinate_texts) { invalid_coordinates } - it 'raises ArgumentError' do + it "raises ArgumentError" do expect { subject.build }.to raise_error(ArgumentError) end end - context 'when coordinates are out of range' do + context "when coordinates are out of range" do let(:coordinate_texts) { out_of_range_coordinates } - it 'raises ArgumentError' do - expect { subject.build }.to raise_error(ArgumentError, 'invalid coordinates') + it "raises ArgumentError" do + expect { subject.build }.to raise_error(ArgumentError, "invalid coordinates") end end - context 'when a hemisphere does not belong to its axis' do + context "when a hemisphere does not belong to its axis" do let(:coordinate_texts) { wrong_axis_hemisphere_coordinates } - it 'raises ArgumentError' do - expect { subject.build }.to raise_error(ArgumentError, 'invalid coordinates') + it "raises ArgumentError" do + expect { subject.build }.to raise_error(ArgumentError, "invalid coordinates") end end - context 'when only some coordinates are unusable' do + context "when only some coordinates are unusable" do let(:coordinate_texts) { out_of_range_coordinates + valid_coordinates } - it 'skips them and builds the rest' do + it "skips them and builds the rest" do expect(subject.build).to eq nav_place end end end - describe '#valid' do - context 'when coordinates are valid' do + describe "#valid" do + context "when coordinates are valid" do let(:coordinate_texts) { valid_coordinates } - it 'returns true' do + it "returns true" do expect(subject.valid?).to be true end end - context 'when coordinates are not present' do + context "when coordinates are not present" do let(:coordinate_texts) { [] } - it 'returns false' do + it "returns false" do expect(subject.valid?).to be false end end - context 'when coordinates are invalid' do + context "when coordinates are invalid" do let(:coordinate_texts) { invalid_coordinates } - it 'returns false' do + it "returns false" do expect(subject.valid?).to be false end end - context 'when coordinates are out of range' do + context "when coordinates are out of range" do let(:coordinate_texts) { out_of_range_coordinates } - it 'returns false instead of raising' do + it "returns false instead of raising" do expect(subject.valid?).to be false end end - context 'when a hemisphere does not belong to its axis' do + context "when a hemisphere does not belong to its axis" do let(:coordinate_texts) { wrong_axis_hemisphere_coordinates } - it 'returns false instead of raising' do + it "returns false instead of raising" do expect(subject.valid?).to be false end end end - describe 'WKT coordinate texts' do - let(:geometries) { JSON.parse(subject.build.to_json)['features'].map { |feature| feature['geometry'] } } + describe "WKT coordinate texts" do + let(:geometries) { JSON.parse(subject.build.to_json)["features"].map { |feature| feature["geometry"] } } - context 'with a point, a box, and a box split at the antimeridian' do + context "with a point, a box, and a box split at the antimeridian" do let(:coordinate_texts) do - ['POINT(-118.243700 34.052200)', - 'POLYGON((-23.900000 33.500000, 53.600000 33.500000, 53.600000 71.316667, -23.900000 71.316667, -23.900000 33.500000))', - 'MULTIPOLYGON(((170.000000 -10.000000, 180.000000 -10.000000, 180.000000 10.000000, 170.000000 10.000000, 170.000000 -10.000000)), ' \ - '((-180.000000 -10.000000, -170.000000 -10.000000, -170.000000 10.000000, -180.000000 10.000000, -180.000000 -10.000000)))'] + ["POINT(-118.243700 34.052200)", + "POLYGON((-23.900000 33.500000, 53.600000 33.500000, 53.600000 71.316667, -23.900000 71.316667, -23.900000 33.500000))", + "MULTIPOLYGON(((170.000000 -10.000000, 180.000000 -10.000000, 180.000000 10.000000, 170.000000 10.000000, 170.000000 -10.000000)), " \ + "((-180.000000 -10.000000, -170.000000 -10.000000, -170.000000 10.000000, -180.000000 10.000000, -180.000000 -10.000000)))"] end - it 'reads each as its GeoJSON geometry' do + it "reads each as its GeoJSON geometry" do expect(geometries).to eq [ - { 'type' => 'Point', 'coordinates' => [-118.2437, 34.0522] }, + {"type" => "Point", "coordinates" => [-118.2437, 34.0522]}, JSON.parse(nav_place[:features][0][:geometry].to_json), - { 'type' => 'MultiPolygon', - 'coordinates' => [ - [[[170.0, -10.0], [180.0, -10.0], [180.0, 10.0], [170.0, 10.0], [170.0, -10.0]]], - [[[-180.0, -10.0], [-170.0, -10.0], [-170.0, 10.0], [-180.0, 10.0], [-180.0, -10.0]]] - ] } + {"type" => "MultiPolygon", + "coordinates" => [ + [[[170.0, -10.0], [180.0, -10.0], [180.0, 10.0], [170.0, 10.0], [170.0, -10.0]]], + [[[-180.0, -10.0], [-170.0, -10.0], [-170.0, 10.0], [-180.0, 10.0], [-180.0, -10.0]]] + ]} ] end end - context 'when rings run the other way' do - let(:coordinate_texts) { ['polygon ((0 0, 0 10, 10 10, 10 0, 0 0), (2 2, 4 2, 4 4, 2 4, 2 2))'] } + context "when rings run the other way" do + let(:coordinate_texts) { ["polygon ((0 0, 0 10, 10 10, 10 0, 0 0), (2 2, 4 2, 4 4, 2 4, 2 2))"] } - it 'turns the exterior counterclockwise and holes clockwise' do + it "turns the exterior counterclockwise and holes clockwise" do expect(geometries).to eq [ - { 'type' => 'Polygon', - 'coordinates' => [ - [[0.0, 0.0], [10.0, 0.0], [10.0, 10.0], [0.0, 10.0], [0.0, 0.0]], - [[2.0, 2.0], [2.0, 4.0], [4.0, 4.0], [4.0, 2.0], [2.0, 2.0]] - ] } + {"type" => "Polygon", + "coordinates" => [ + [[0.0, 0.0], [10.0, 0.0], [10.0, 10.0], [0.0, 10.0], [0.0, 0.0]], + [[2.0, 2.0], [2.0, 4.0], [4.0, 4.0], [4.0, 2.0], [2.0, 2.0]] + ]} ] end end - context 'alongside other coordinate texts' do - let(:coordinate_texts) { ['E 103°48ʹ/S 3°46ʹ).', 'POINT(1.5 2.5)'] } + context "alongside other coordinate texts" do + let(:coordinate_texts) { ["E 103°48ʹ/S 3°46ʹ).", "POINT(1.5 2.5)"] } - it 'keeps their order' do + it "keeps their order" do expect(geometries).to eq [ - { 'type' => 'Point', 'coordinates' => [103.8, -3.766667] }, - { 'type' => 'Point', 'coordinates' => [1.5, 2.5] } + {"type" => "Point", "coordinates" => [103.8, -3.766667]}, + {"type" => "Point", "coordinates" => [1.5, 2.5]} ] end end - context 'when the WKT cannot be used' do + context "when the WKT cannot be used" do let(:coordinate_texts) do - ['POINT(200 0)', 'POINT(1 2 3)', 'POINT EMPTY', 'POLYGON((0 0, 1 1))', 'POLYGON((0 0, 1 0, 1 1, 0 1, 0 2))', - 'POLYGON((0 0, 1 0, 1 1, 0 0', 'MULTIPOLYGON()', 'LINESTRING(0 0, 1 1)'] + ["POINT(200 0)", "POINT(1 2 3)", "POINT EMPTY", "POLYGON((0 0, 1 1))", "POLYGON((0 0, 1 0, 1 1, 0 1, 0 2))", + "POLYGON((0 0, 1 0, 1 1, 0 0", "MULTIPOLYGON()", "LINESTRING(0 0, 1 1)"] end - it 'skips it' do + it "skips it" do expect(subject.valid?).to be false end end diff --git a/spec/unit/iiif/v3/presentation/range_spec.rb b/spec/unit/iiif/v3/presentation/range_spec.rb index 52d9fdf..6193a92 100644 --- a/spec/unit/iiif/v3/presentation/range_spec.rb +++ b/spec/unit/iiif/v3/presentation/range_spec.rb @@ -1,71 +1,70 @@ describe IIIF::V3::Presentation::Range do - let(:fixed_values) do { - 'id' => 'http://www.example.org/iiif/book1/range/r1', - 'type' => 'Range', - 'label' => 'Introduction', - 'members' => [ + "id" => "http://www.example.org/iiif/book1/range/r1", + "type" => "Range", + "label" => "Introduction", + "members" => [ { - "id" => 'http://www.example.org/iiif/book1/range/r1-1', + "id" => "http://www.example.org/iiif/book1/range/r1-1", "type" => "Range" }, { - "id" => 'http://www.example.org/iiif/book1/range/r1-2', + "id" => "http://www.example.org/iiif/book1/range/r1-2", "type" => "Range" }, { - "id" => 'http://www.example.org/iiif/book1/canvas/p1', + "id" => "http://www.example.org/iiif/book1/canvas/p1", "type" => "Canvas" }, { - "id" => 'http://www.example.org/iiif/book1/canvas/p2', + "id" => "http://www.example.org/iiif/book1/canvas/p2", "type" => "Canvas" }, { - "id" => 'http://www.example.org/iiif/book1/canvas/p3#xywh=0,0,750,300', + "id" => "http://www.example.org/iiif/book1/canvas/p3#xywh=0,0,750,300", "type" => "Canvas" } ] } end - describe '#initialize' do - it 'sets type to Range by default' do - expect(subject['type']).to eq 'Range' + describe "#initialize" do + it "sets type to Range by default" do + expect(subject["type"]).to eq "Range" end end describe "#{described_class}.define_methods_for_array_only_keys" do - it_behaves_like 'it has the appropriate methods for array-only keys v3' + it_behaves_like "it has the appropriate methods for array-only keys v3" end describe "#{described_class}.define_methods_for_string_only_keys" do - it_behaves_like 'it has the appropriate methods for string-only keys v3' + it_behaves_like "it has the appropriate methods for string-only keys v3" end describe "#{described_class}.define_methods_for_any_type_keys" do - it_behaves_like 'it has the appropriate methods for any-type keys v3' + it_behaves_like "it has the appropriate methods for any-type keys v3" end - describe '#validate' do + describe "#validate" do let(:bad_val_msg) do - "All entries in the (items or canvases) array must be one of #{IIIF::V3::Presentation::Range::VALID_ITEM_TYPES.join(', ')}" + "All entries in the (items or canvases) array must be one of #{IIIF::V3::Presentation::Range::VALID_ITEM_TYPES.join(", ")}" end - describe 'items' do - it 'raises IllegalValueError for items entry that is not valid type' do - subject['id'] = 'test_range' - subject['label'] = { 'en' => ['Test Range'] } - subject['items'] = [IIIF::V3::Presentation::Range.new('id' => 'child_range', 'label' => ['Child Label']), - IIIF::V3::Presentation::AnnotationPage.new] + describe "items" do + it "raises IllegalValueError for items entry that is not valid type" do + subject["id"] = "test_range" + subject["label"] = {"en" => ["Test Range"]} + subject["items"] = [IIIF::V3::Presentation::Range.new("id" => "child_range", "label" => ["Child Label"]), + IIIF::V3::Presentation::AnnotationPage.new] expect { subject.validate }.to raise_error(IIIF::V3::Presentation::IllegalValueError, bad_val_msg) end end - describe 'canvases' do - it 'raises IllegalValueError for canvases entry that is not valid type' do - subject['id'] = 'test_range' - subject['label'] = { 'en' => ['Test Range'] } - subject['canvases'] = [IIIF::V3::Presentation::Canvas.new, IIIF::V3::Presentation::AnnotationPage.new] + describe "canvases" do + it "raises IllegalValueError for canvases entry that is not valid type" do + subject["id"] = "test_range" + subject["label"] = {"en" => ["Test Range"]} + subject["canvases"] = [IIIF::V3::Presentation::Canvas.new, IIIF::V3::Presentation::AnnotationPage.new] expect { subject.validate }.to raise_error(IIIF::V3::Presentation::IllegalValueError, bad_val_msg) end end diff --git a/spec/unit/iiif/v3/presentation/resource_spec.rb b/spec/unit/iiif/v3/presentation/resource_spec.rb index 4dd5e48..d6a2b5c 100644 --- a/spec/unit/iiif/v3/presentation/resource_spec.rb +++ b/spec/unit/iiif/v3/presentation/resource_spec.rb @@ -1,147 +1,149 @@ describe IIIF::V3::Presentation::Resource do - describe '#required_keys' do - it 'id' do - expect(subject.required_keys).to include('id') + describe "#required_keys" do + it "id" do + expect(subject.required_keys).to include("id") end - it 'type' do - expect(subject.required_keys).to include('type') + it "type" do + expect(subject.required_keys).to include("type") end end - describe '#prohibited_keys' do - it 'contains the expected key names' do + describe "#prohibited_keys" do + it "contains the expected key names" do keys = described_class::PAGING_PROPERTIES + - %w{ + %w[ nav_date viewing_direction start_canvas content_annotations - } + ] expect(subject.prohibited_keys).to include(*keys) end end - describe '#uri_only_keys' do - it 'id' do - expect(subject.uri_only_keys).to include('id') + describe "#uri_only_keys" do + it "id" do + expect(subject.uri_only_keys).to include("id") end end - describe '#initialize' do - it 'allows subclasses to override type' do + describe "#initialize" do + it "allows subclasses to override type" do subclass = Class.new(described_class) do - def initialize(hsh={}) - hsh = { 'type' => 'a:SubClass' } - super(hsh) + def initialize(_hsh = {}) + super({"type" => "a:SubClass"}) end end sub = subclass.new - expect(sub['type']).to eq 'a:SubClass' + expect(sub["type"]).to eq "a:SubClass" end end - describe '#validate' do - it 'raises an IllegalValueError if id is not URI' do - subject['id'] = 'foo' - subject['type'] = 'image/jpeg' + describe "#validate" do + it "raises an IllegalValueError if id is not URI" do + subject["id"] = "foo" + subject["type"] = "image/jpeg" exp_err_msg = "id value must be a String containing a URI for #{described_class}" expect { subject.validate }.to raise_error(IIIF::V3::Presentation::IllegalValueError, exp_err_msg) end - it 'raises an IllegalValueError if id is not http' do - subject['id'] = 'ftp://www.example.org' - subject['type'] = 'image/jpeg' + it "raises an IllegalValueError if id is not http" do + subject["id"] = "ftp://www.example.org" + subject["type"] = "image/jpeg" exp_err_msg = "id must be an http(s) URI for #{described_class}" expect { subject.validate }.to raise_error(IIIF::V3::Presentation::IllegalValueError, exp_err_msg) end end - describe 'realistic examples' do - describe 'non-image examples from http://prezi3.iiif.io/api/presentation/3.0' do - describe 'audio' do - let(:file_id) { 'http://example.org/iiif/book1/res/music.mp3' } - let(:file_type) { 'dctypes:Sound' } - let(:file_mimetype) { 'audio/mpeg' } - let(:resource_object) { IIIF::V3::Presentation::Resource.new({ - 'id' => file_id, - 'type' => file_type, - 'format' => file_mimetype - })} - it 'validates' do - expect{resource_object.validate}.not_to raise_error + describe "realistic examples" do + describe "non-image examples from http://prezi3.iiif.io/api/presentation/3.0" do + describe "audio" do + let(:file_id) { "http://example.org/iiif/book1/res/music.mp3" } + let(:file_type) { "dctypes:Sound" } + let(:file_mimetype) { "audio/mpeg" } + let(:resource_object) { + IIIF::V3::Presentation::Resource.new({ + "id" => file_id, + "type" => file_type, + "format" => file_mimetype + }) + } + it "validates" do + expect { resource_object.validate }.not_to raise_error end - it 'has expected required values' do + it "has expected required values" do expect(resource_object.id).to eq file_id end - it 'has expected other values' do + it "has expected other values" do expect(resource_object.type).to eq file_type expect(resource_object.format).to eq file_mimetype expect(resource_object.service).to eq [] end end - describe 'text' do - let(:file_id) { 'http://example.org/iiif/book1/res/tei-text-p1.xml' } - let(:file_type) { 'dctypes:Text' } - let(:file_mimetype) { 'application/tei+xml' } - let(:resource_object) { IIIF::V3::Presentation::Resource.new({ - 'id' => file_id, - 'type' => file_type, - 'format' => file_mimetype - })} - it 'validates' do - expect{resource_object.validate}.not_to raise_error + describe "text" do + let(:file_id) { "http://example.org/iiif/book1/res/tei-text-p1.xml" } + let(:file_type) { "dctypes:Text" } + let(:file_mimetype) { "application/tei+xml" } + let(:resource_object) { + IIIF::V3::Presentation::Resource.new({ + "id" => file_id, + "type" => file_type, + "format" => file_mimetype + }) + } + it "validates" do + expect { resource_object.validate }.not_to raise_error end - it 'has expected required values' do + it "has expected required values" do expect(resource_object.id).to eq file_id end - it 'has expected other values' do + it "has expected other values" do expect(resource_object.type).to eq file_type expect(resource_object.format).to eq file_mimetype expect(resource_object.service).to eq [] end end - end - describe 'stanford' do - describe 'non-image resource per purl code' do - let(:file_id) { 'https://example.org/file/abc666/ocr.txt' } - let(:file_type) { 'Document' } - let(:file_mimetype) { 'text/plain' } + describe "stanford" do + describe "non-image resource per purl code" do + let(:file_id) { "https://example.org/file/abc666/ocr.txt" } + let(:file_type) { "Document" } + let(:file_mimetype) { "text/plain" } let(:resource_object) { resource = IIIF::V3::Presentation::Resource.new - resource['id'] = file_id - resource['type'] = file_type + resource["id"] = file_id + resource["type"] = file_type resource.format = file_mimetype resource } - describe 'world visible' do - it 'validates' do - expect{resource_object.validate}.not_to raise_error + describe "world visible" do + it "validates" do + expect { resource_object.validate }.not_to raise_error end - it 'has expected required values' do + it "has expected required values" do expect(resource_object.id).to eq file_id end - it 'has expected other values' do + it "has expected other values" do expect(resource_object.type).to eq file_type expect(resource_object.format).to eq file_mimetype expect(resource_object.service).to eq [] end end - describe 'requires login' do + describe "requires login" do # let(:auth_token_service) { # IIIF::V3::Presentation::Service.new({ # 'id' => 'https://example.org/image/iiif/token', # 'profile' => IIIF::V3::Presentation::Service::IIIF_AUTHENTICATION_V1_TOKEN_PROFILE # })} - let(:service_label) { 'login message' } - let(:token_service_id) { 'https://example.org/iiif/token' } + let(:service_label) { "login message" } + let(:token_service_id) { "https://example.org/iiif/token" } let(:login_service) { IIIF::V3::Presentation::Service.new( - 'id' => 'https://example.org/auth/iiif', - 'profile' => 'http://iiif.io/api/auth/1/login', - 'label' => service_label, - 'service' => [{ - 'id' => token_service_id, - 'profile' => 'http://iiif.io/api/auth/1/token' + "id" => "https://example.org/auth/iiif", + "profile" => "http://iiif.io/api/auth/1/login", + "label" => service_label, + "service" => [{ + "id" => token_service_id, + "profile" => "http://iiif.io/api/auth/1/token" }] ) } @@ -150,25 +152,24 @@ def initialize(hsh={}) resource.service = [login_service] resource } - it 'validates' do - expect{resource_object_w_login.validate}.not_to raise_error + it "validates" do + expect { resource_object_w_login.validate }.not_to raise_error end - it 'has expected service value' do + it "has expected service value" do service_obj = resource_object_w_login.service.first expect(service_obj.class).to eq IIIF::V3::Presentation::Service expect(service_obj.keys.size).to eq 4 - expect(service_obj.id).to eq 'https://example.org/auth/iiif' + expect(service_obj.id).to eq "https://example.org/auth/iiif" expect(service_obj.profile).to eq IIIF::V3::Presentation::Service::IIIF_AUTHENTICATION_V1_LOGIN_PROFILE expect(service_obj.label).to eq service_label expect(service_obj.service.class).to eq Array expect(service_obj.service.size).to eq 1 expect(service_obj.service.first.keys.size).to eq 2 - expect(service_obj.service.first['id']).to eq token_service_id - expect(service_obj.service.first['profile']).to eq IIIF::V3::Presentation::Service::IIIF_AUTHENTICATION_V1_TOKEN_PROFILE + expect(service_obj.service.first["id"]).to eq token_service_id + expect(service_obj.service.first["profile"]).to eq IIIF::V3::Presentation::Service::IIIF_AUTHENTICATION_V1_TOKEN_PROFILE end end end end end - end diff --git a/spec/unit/iiif/v3/presentation/sequence_spec.rb b/spec/unit/iiif/v3/presentation/sequence_spec.rb index d210fc4..841563f 100644 --- a/spec/unit/iiif/v3/presentation/sequence_spec.rb +++ b/spec/unit/iiif/v3/presentation/sequence_spec.rb @@ -1,212 +1,218 @@ describe IIIF::V3::Presentation::Sequence do - - describe '#required_keys' do + describe "#required_keys" do # NOTE: relaxing requirement for items as Universal Viewer currently only accepts canvases # see https://github.com/sul-dlss/osullivan/issues/27, sul-dlss/purl/issues/167 # %w{ type items }.each do |k| - %w{ type }.each do |k| + %w[type].each do |k| it k do expect(subject.required_keys).to include(k) end end end - describe '#prohibited_keys' do - it 'contains the expected key names' do + describe "#prohibited_keys" do + it "contains the expected key names" do keys = described_class::CONTENT_RESOURCE_PROPERTIES + described_class::PAGING_PROPERTIES + - %w{ + %w[ nav_date content_annotations - } + ] expect(subject.prohibited_keys).to include(*keys) end end - describe '#array_only_keys' do - it 'items' do - expect(subject.array_only_keys).to include('items') + describe "#array_only_keys" do + it "items" do + expect(subject.array_only_keys).to include("items") end # NOTE: also allowing sequences as Universal Viewer currently only accepts canvases # see https://github.com/sul-dlss/osullivan/issues/27, sul-dlss/purl/issues/167 - it 'canvases' do - expect(subject.array_only_keys).to include('canvases') + it "canvases" do + expect(subject.array_only_keys).to include("canvases") end end - describe '#legal_viewing_hint_values' do - it 'contains the expected values' do - expect(subject.legal_viewing_hint_values).to contain_exactly('individuals', 'paged', 'continuous', 'auto-advance') + describe "#legal_viewing_hint_values" do + it "contains the expected values" do + expect(subject.legal_viewing_hint_values).to contain_exactly("individuals", "paged", "continuous", "auto-advance") end end - describe '#initialize' do - it 'sets type to Sequence by default' do - expect(subject['type']).to eq 'Sequence' + describe "#initialize" do + it "sets type to Sequence by default" do + expect(subject["type"]).to eq "Sequence" end - it 'allows subclasses to override type' do + it "allows subclasses to override type" do subclass = Class.new(described_class) do - def initialize(hsh={}) - hsh = { 'type' => 'a:SubClass' } - super(hsh) + def initialize(_hsh = {}) + super({"type" => "a:SubClass"}) end end sub = subclass.new - expect(sub['type']).to eq 'a:SubClass' + expect(sub["type"]).to eq "a:SubClass" end end - describe '#validate' do + describe "#validate" do let(:req_key_msg) { "The (items or canvases) list must have at least one entry." } - it 'raises MissingRequiredKeyError if no items or canvases key' do + it "raises MissingRequiredKeyError if no items or canvases key" do expect { subject.validate }.to raise_error(IIIF::V3::Presentation::MissingRequiredKeyError, req_key_msg) end - describe 'items' do - it 'raises MissingRequiredKeyError for items as empty Array' do - subject['items'] = [] + describe "items" do + it "raises MissingRequiredKeyError for items as empty Array" do + subject["items"] = [] expect { subject.validate }.to raise_error(IIIF::V3::Presentation::MissingRequiredKeyError, req_key_msg) end end - describe 'canvases' do - it 'raises MissingRequiredKeyError for canvases as empty Array' do - subject['items'] = [] + describe "canvases" do + it "raises MissingRequiredKeyError for canvases as empty Array" do + subject["items"] = [] expect { subject.validate }.to raise_error(IIIF::V3::Presentation::MissingRequiredKeyError, req_key_msg) end end end - describe 'realistic examples' do - let!(:canvas_object) { IIIF::V3::Presentation::Canvas.new({ - "id" => "https://example.org/abc666/iiif3/canvas/0001", - "label" => "p. 1", - "height" => 7579, - "width" => 10108, - "content" => [] - })} - describe 'minimal sequence' do - let!(:sequence_object) { described_class.new({ - "items" => [canvas_object] - })} - it 'validates' do - expect{sequence_object.validate}.not_to raise_error + describe "realistic examples" do + let!(:canvas_object) { + IIIF::V3::Presentation::Canvas.new({ + "id" => "https://example.org/abc666/iiif3/canvas/0001", + "label" => "p. 1", + "height" => 7579, + "width" => 10108, + "content" => [] + }) + } + describe "minimal sequence" do + let!(:sequence_object) { + described_class.new({ + "items" => [canvas_object] + }) + } + it "validates" do + expect { sequence_object.validate }.not_to raise_error end - it 'has expected required values' do - expect(sequence_object.type).to eq 'Sequence' + it "has expected required values" do + expect(sequence_object.type).to eq "Sequence" expect(sequence_object.items.size).to be 1 expect(sequence_object.items.first).to eq canvas_object end end - describe 'example from Stanford purl' do - let(:seq_id) { 'https://example.org/abc666#sequence-1' } + describe "example from Stanford purl" do + let(:seq_id) { "https://example.org/abc666#sequence-1" } let(:sequence_object) { s = described_class.new({ - "id" => seq_id, - "label" => "Current order" + "id" => seq_id, + "label" => "Current order" }) s.canvases << canvas_object s } - it 'validates' do - expect{sequence_object.validate}.not_to raise_error + it "validates" do + expect { sequence_object.validate }.not_to raise_error end - it 'has expected required values' do - expect(sequence_object.type).to eq 'Sequence' + it "has expected required values" do + expect(sequence_object.type).to eq "Sequence" expect(sequence_object.canvases.size).to be 1 expect(sequence_object.canvases.first).to eq canvas_object end - it 'has expected string values' do + it "has expected string values" do expect(sequence_object.id).to eq seq_id expect(sequence_object.label).to eq "Current order" end - describe 'with viewingDirection' do + describe "with viewingDirection" do let(:sequence_vd) { - sequence_object.viewingDirection = 'left-to-right' + sequence_object.viewingDirection = "left-to-right" sequence_object } - it 'validates' do - expect{sequence_vd.validate}.not_to raise_error + it "validates" do + expect { sequence_vd.validate }.not_to raise_error end - it 'has expected required values' do - expect(sequence_vd.type).to eq 'Sequence' + it "has expected required values" do + expect(sequence_vd.type).to eq "Sequence" expect(sequence_vd.canvases.size).to be 1 expect(sequence_vd.canvases.first).to eq canvas_object end - it 'has expected string values' do + it "has expected string values" do expect(sequence_vd.id).to eq seq_id expect(sequence_vd.label).to eq "Current order" - expect(sequence_vd.viewing_direction).to eq 'left-to-right' - expect(sequence_vd.viewingDirection).to eq 'left-to-right' + expect(sequence_vd.viewing_direction).to eq "left-to-right" + expect(sequence_vd.viewingDirection).to eq "left-to-right" end end end - describe 'example from http://prezi3.iiif.io/api/presentation/3.0' do - let!(:sequence_object) { described_class.new({ - "id" => "http://example.org/iiif/book1/sequence/normal", - "label" => {"en" => "Current Page Order"}, - "viewingDirection" => "left-to-right", - "viewingHint" => ["paged"], - "startCanvas" => canvas_object.id, - "items" => [canvas_object] - })} - it 'validates' do - expect{sequence_object.validate}.not_to raise_error + describe "example from http://prezi3.iiif.io/api/presentation/3.0" do + let!(:sequence_object) { + described_class.new({ + "id" => "http://example.org/iiif/book1/sequence/normal", + "label" => {"en" => "Current Page Order"}, + "viewingDirection" => "left-to-right", + "viewingHint" => ["paged"], + "startCanvas" => canvas_object.id, + "items" => [canvas_object] + }) + } + it "validates" do + expect { sequence_object.validate }.not_to raise_error end - it 'has expected required values' do - expect(sequence_object.type).to eq 'Sequence' + it "has expected required values" do + expect(sequence_object.type).to eq "Sequence" expect(sequence_object.items.size).to be 1 expect(sequence_object.items.first).to eq canvas_object end - it 'has expected string values' do + it "has expected string values" do expect(sequence_object.id).to eq "http://example.org/iiif/book1/sequence/normal" expect(sequence_object.viewingDirection).to eq "left-to-right" expect(sequence_object.startCanvas).to eq "https://example.org/abc666/iiif3/canvas/0001" end - it 'has expected additional content' do + it "has expected additional content" do expect(sequence_object.viewingHint).to eq ["paged"] - expect(sequence_object.label).to eq ({"en" => "Current Page Order"}) + expect(sequence_object.label).to eq({"en" => "Current Page Order"}) end end - describe 'another example' do - let!(:sequence_object) { described_class.new({ - "id" => "http://example.com/prefix/sequence/456", - 'label' => 'Book 1', - 'description' => 'A longer description of this example book. It should give some real information.', - 'thumbnail' => [{ - 'id' => 'http://www.example.org/images/book1-page1/full/80,100/0/default.jpg', - 'type' => 'Image', - 'service'=> [{ - '@context' => 'http://iiif.io/api/image/2/context.json', - 'id' => 'http://www.example.org/images/book1-page1', - 'profile' => 'http://iiif.io/api/image/2/level1.json' - }] - }], - 'attribution' => 'Provided by Example Organization', - 'rights' => 'Sample rights', - 'logo' => 'http://www.example.org/logos/institution1.jpg', - 'see_also' => 'http://www.example.org/library/catalog/book1.xml', - 'service' => [{ - '@context' => 'http://example.org/ns/jsonld/context.json', - 'id' => 'http://example.org/service/example', - 'profile' => 'http://example.org/docs/example-service.html' - }], - 'related' => { - 'id' => 'http://www.example.org/videos/video-book1.mpg', - 'format' => 'video/mpeg' - }, - 'within' => 'http://www.example.org/collections/books/', - # Sequence - 'metadata' => [{'label'=>'Author', 'value'=>'Anne Author'}], - "items" => [canvas_object], - 'start_canvas' => 'http://www.example.org/iiif/book1/canvas/p2', - "viewingDirection" => "left-to-right", - "viewingHint" => ["paged"], - "startCanvas" => canvas_object.id, - })} - it 'validates' do - expect{sequence_object.validate}.not_to raise_error + describe "another example" do + let!(:sequence_object) { + described_class.new({ + "id" => "http://example.com/prefix/sequence/456", + "label" => "Book 1", + "description" => "A longer description of this example book. It should give some real information.", + "thumbnail" => [{ + "id" => "http://www.example.org/images/book1-page1/full/80,100/0/default.jpg", + "type" => "Image", + "service" => [{ + "@context" => "http://iiif.io/api/image/2/context.json", + "id" => "http://www.example.org/images/book1-page1", + "profile" => "http://iiif.io/api/image/2/level1.json" + }] + }], + "attribution" => "Provided by Example Organization", + "rights" => "Sample rights", + "logo" => "http://www.example.org/logos/institution1.jpg", + "see_also" => "http://www.example.org/library/catalog/book1.xml", + "service" => [{ + "@context" => "http://example.org/ns/jsonld/context.json", + "id" => "http://example.org/service/example", + "profile" => "http://example.org/docs/example-service.html" + }], + "related" => { + "id" => "http://www.example.org/videos/video-book1.mpg", + "format" => "video/mpeg" + }, + "within" => "http://www.example.org/collections/books/", + # Sequence + "metadata" => [{"label" => "Author", "value" => "Anne Author"}], + "items" => [canvas_object], + "start_canvas" => "http://www.example.org/iiif/book1/canvas/p2", + "viewingDirection" => "left-to-right", + "viewingHint" => ["paged"], + "startCanvas" => canvas_object.id + }) + } + it "validates" do + expect { sequence_object.validate }.not_to raise_error end end end diff --git a/spec/unit/iiif/v3/presentation/service_spec.rb b/spec/unit/iiif/v3/presentation/service_spec.rb index c4e3533..b1e4802 100644 --- a/spec/unit/iiif/v3/presentation/service_spec.rb +++ b/spec/unit/iiif/v3/presentation/service_spec.rb @@ -1,88 +1,87 @@ describe IIIF::V3::Presentation::Service do - - describe '#required_keys' do + describe "#required_keys" do it '"type" is not required' do - expect(subject.required_keys).not_to include('type') + expect(subject.required_keys).not_to include("type") end end - describe '#prohibited_keys' do - it 'contains the expected key names' do + describe "#prohibited_keys" do + it "contains the expected key names" do keys = described_class::CONTENT_RESOURCE_PROPERTIES + described_class::PAGING_PROPERTIES + - %w{ + %w[ nav_date viewing_direction start_canvas content_annotations - } + ] expect(subject.prohibited_keys).to include(*keys) end end - describe '#uri_only_keys' do - it '@context' do - expect(subject.uri_only_keys).to include('@context') + describe "#uri_only_keys" do + it "@context" do + expect(subject.uri_only_keys).to include("@context") end - it '@id' do - expect(subject.uri_only_keys).to include('@id') + it "@id" do + expect(subject.uri_only_keys).to include("@id") end - it 'id' do - expect(subject.uri_only_keys).to include('id') + it "id" do + expect(subject.uri_only_keys).to include("id") end end - describe '#any_type_keys' do - it 'profile' do - expect(subject.any_type_keys).to include('profile') + describe "#any_type_keys" do + it "profile" do + expect(subject.any_type_keys).to include("profile") end end let(:id_uri) { "https://example.org/image1" } - describe '#initialize' do - it 'assigns hash values passed in' do - label_val = 'foo' - inner_service_id = 'http://example.org/whatever' - inner_service_profile = 'http://iiif.io/api/auth/1/token' + describe "#initialize" do + it "assigns hash values passed in" do + label_val = "foo" + inner_service_id = "http://example.org/whatever" + inner_service_profile = "http://iiif.io/api/auth/1/token" inner_service_val = described_class.new({ - 'id' => inner_service_id, - 'profile' => inner_service_profile - }) + "id" => inner_service_id, + "profile" => inner_service_profile + }) service_obj = described_class.new({ - 'type' => described_class::IIIF_IMAGE_V2_TYPE, - 'id' => id_uri, - 'profile' => described_class::IIIF_IMAGE_V2_LEVEL1_PROFILE, - 'label' => label_val, - 'service' => [inner_service_val] + "type" => described_class::IIIF_IMAGE_V2_TYPE, + "id" => id_uri, + "profile" => described_class::IIIF_IMAGE_V2_LEVEL1_PROFILE, + "label" => label_val, + "service" => [inner_service_val] }) expect(service_obj.keys.size).to eq 5 - expect(service_obj['id']).to eq id_uri - expect(service_obj['type']).to eq described_class::IIIF_IMAGE_V2_TYPE - expect(service_obj['profile']).to eq described_class::IIIF_IMAGE_V2_LEVEL1_PROFILE - expect(service_obj['label']).to eq label_val - expect(service_obj['service'][0]['id']).to eq inner_service_id - expect(service_obj['service'][0]['profile']).to eq inner_service_profile + expect(service_obj["id"]).to eq id_uri + expect(service_obj["type"]).to eq described_class::IIIF_IMAGE_V2_TYPE + expect(service_obj["profile"]).to eq described_class::IIIF_IMAGE_V2_LEVEL1_PROFILE + expect(service_obj["label"]).to eq label_val + expect(service_obj["service"][0]["id"]).to eq inner_service_id + expect(service_obj["service"][0]["profile"]).to eq inner_service_profile end it 'allows both "id" and "@id" as keys' do id_uri = "https://stacks.stanford.edu/image/iiif/wy534zh7137%2FSULAIR_rosette" service_obj = described_class.new({ - 'id' => id_uri, - '@id' => id_uri + "id" => id_uri, + "@id" => id_uri }) expect(service_obj.keys.size).to eq 2 - expect(service_obj['id']).to eq id_uri - expect(service_obj['@id']).to eq id_uri + expect(service_obj["id"]).to eq id_uri + expect(service_obj["@id"]).to eq id_uri end - it 'allows non-URI profile value' do - expect{ + it "allows non-URI profile value" do + expect { described_class.new({ "profile" => [ "http://iiif.io/api/image/2/level2.json", { - "formats" => [ "gif", "pdf" ], - "qualities" => [ "color", "gray" ], - "supports" => [ "canonicalLinkHeader", "rotationArbitrary", "http://example.com/feature" ] + "formats" => ["gif", "pdf"], + "qualities" => ["color", "gray"], + "supports" => ["canonicalLinkHeader", "rotationArbitrary", "http://example.com/feature"] } ] }) @@ -90,111 +89,111 @@ end end - describe '#validate' do - describe 'type = IIIF_IMAGE_API_V2_TYPE' do + describe "#validate" do + describe "type = IIIF_IMAGE_API_V2_TYPE" do it 'must have a "@id" or "id"' do service_obj = described_class.new({ - 'type' => described_class::IIIF_IMAGE_V2_TYPE, - 'nope' => id_uri, - 'profile' => described_class::IIIF_IMAGE_V2_LEVEL1_PROFILE - }) - exp_err_msg = 'id or @id values are required for IIIF::V3::Presentation::Service with type or @type ImageService2' - expect{service_obj.validate}.to raise_error(IIIF::V3::Presentation::MissingRequiredKeyError, exp_err_msg) + "type" => described_class::IIIF_IMAGE_V2_TYPE, + "nope" => id_uri, + "profile" => described_class::IIIF_IMAGE_V2_LEVEL1_PROFILE + }) + exp_err_msg = "id or @id values are required for IIIF::V3::Presentation::Service with type or @type ImageService2" + expect { service_obj.validate }.to raise_error(IIIF::V3::Presentation::MissingRequiredKeyError, exp_err_msg) end - it 'should have a profile' do + it "should have a profile" do service_obj = described_class.new({ - '@type' => described_class::IIIF_IMAGE_V2_TYPE, - '@id' => id_uri - }) - exp_err_msg = 'profile should be present for IIIF::V3::Presentation::Service with type or @type ImageService2' - expect{service_obj.validate}.to raise_error(IIIF::V3::Presentation::MissingRequiredKeyError, exp_err_msg) + "@type" => described_class::IIIF_IMAGE_V2_TYPE, + "@id" => id_uri + }) + exp_err_msg = "profile should be present for IIIF::V3::Presentation::Service with type or @type ImageService2" + expect { service_obj.validate }.to raise_error(IIIF::V3::Presentation::MissingRequiredKeyError, exp_err_msg) end it 'should have matching values for "@id" and "id" if both are specified' do service_obj = described_class.new({ - '@type' => described_class::IIIF_IMAGE_V2_TYPE, - '@id' => id_uri, - 'id' => "#{id_uri}/foo", - 'profile' => described_class::IIIF_IMAGE_V2_LEVEL1_PROFILE - }) - exp_err_msg = 'id and @id values must match for IIIF::V3::Presentation::Service with type or @type ImageService2' - expect{service_obj.validate}.to raise_error(IIIF::V3::Presentation::IllegalValueError, exp_err_msg) + "@type" => described_class::IIIF_IMAGE_V2_TYPE, + "@id" => id_uri, + "id" => "#{id_uri}/foo", + "profile" => described_class::IIIF_IMAGE_V2_LEVEL1_PROFILE + }) + exp_err_msg = "id and @id values must match for IIIF::V3::Presentation::Service with type or @type ImageService2" + expect { service_obj.validate }.to raise_error(IIIF::V3::Presentation::IllegalValueError, exp_err_msg) end end end - describe 'realistic examples' do - describe 'from Stanford purl manifests' do - it 'iiif image v2 service' do + describe "realistic examples" do + describe "from Stanford purl manifests" do + it "iiif image v2 service" do service_obj = described_class.new({ - 'type' => described_class::IIIF_IMAGE_V2_TYPE, - 'id' => id_uri, - '@id' => id_uri, - 'profile' => described_class::IIIF_IMAGE_V2_LEVEL1_PROFILE + "type" => described_class::IIIF_IMAGE_V2_TYPE, + "id" => id_uri, + "@id" => id_uri, + "profile" => described_class::IIIF_IMAGE_V2_LEVEL1_PROFILE }) - expect{service_obj.validate}.not_to raise_error + expect { service_obj.validate }.not_to raise_error expect(service_obj.keys.size).to eq 4 - expect(service_obj.keys).to include('type', '@id', 'id', 'profile') - expect(service_obj['type']).to eq described_class::IIIF_IMAGE_V2_TYPE - expect(service_obj['id']).to eq id_uri - expect(service_obj['@id']).to eq id_uri - expect(service_obj['profile']).to eq described_class::IIIF_IMAGE_V2_LEVEL1_PROFILE + expect(service_obj.keys).to include("type", "@id", "id", "profile") + expect(service_obj["type"]).to eq described_class::IIIF_IMAGE_V2_TYPE + expect(service_obj["id"]).to eq id_uri + expect(service_obj["@id"]).to eq id_uri + expect(service_obj["profile"]).to eq described_class::IIIF_IMAGE_V2_LEVEL1_PROFILE end - it 'login service' do + it "login service" do token_service = described_class.new({ - 'id' => 'https://example.org/image/iiif/token', - 'profile' => described_class::IIIF_AUTHENTICATION_V1_TOKEN_PROFILE + "id" => "https://example.org/image/iiif/token", + "profile" => described_class::IIIF_AUTHENTICATION_V1_TOKEN_PROFILE }) - expect{token_service.validate}.not_to raise_error + expect { token_service.validate }.not_to raise_error expect(token_service.class).to eq described_class expect(token_service.keys.size).to eq 2 - expect(token_service.keys).to include('id', 'profile') - expect(token_service['id']).to eq 'https://example.org/image/iiif/token' - expect(token_service['profile']).to eq described_class::IIIF_AUTHENTICATION_V1_TOKEN_PROFILE + expect(token_service.keys).to include("id", "profile") + expect(token_service["id"]).to eq "https://example.org/image/iiif/token" + expect(token_service["profile"]).to eq described_class::IIIF_AUTHENTICATION_V1_TOKEN_PROFILE service_obj = described_class.new( - 'id' => 'https://example.org/auth/iiif', - 'profile' => described_class::IIIF_AUTHENTICATION_V1_LOGIN_PROFILE, - 'label' => 'label value', - 'service' => [token_service] + "id" => "https://example.org/auth/iiif", + "profile" => described_class::IIIF_AUTHENTICATION_V1_LOGIN_PROFILE, + "label" => "label value", + "service" => [token_service] ) - expect{service_obj.validate}.not_to raise_error + expect { service_obj.validate }.not_to raise_error expect(service_obj.keys.size).to eq 4 - expect(service_obj.keys).to include('id', 'profile', 'label', 'service') - expect(service_obj['id']).to eq 'https://example.org/auth/iiif' - expect(service_obj['profile']).to eq described_class::IIIF_AUTHENTICATION_V1_LOGIN_PROFILE - expect(service_obj['label']).to eq 'label value' - inner_service = service_obj['service'][0] + expect(service_obj.keys).to include("id", "profile", "label", "service") + expect(service_obj["id"]).to eq "https://example.org/auth/iiif" + expect(service_obj["profile"]).to eq described_class::IIIF_AUTHENTICATION_V1_LOGIN_PROFILE + expect(service_obj["label"]).to eq "label value" + inner_service = service_obj["service"][0] expect(inner_service.class).to eq described_class - expect{inner_service.validate}.not_to raise_error + expect { inner_service.validate }.not_to raise_error expect(inner_service.keys.size).to eq 2 - expect(inner_service.keys).to include('id', 'profile') - expect(inner_service['id']).to eq 'https://example.org/image/iiif/token' - expect(inner_service['profile']).to eq described_class::IIIF_AUTHENTICATION_V1_TOKEN_PROFILE + expect(inner_service.keys).to include("id", "profile") + expect(inner_service["id"]).to eq "https://example.org/image/iiif/token" + expect(inner_service["profile"]).to eq described_class::IIIF_AUTHENTICATION_V1_TOKEN_PROFILE end - it 'triply nested service' do + it "triply nested service" do inner = described_class.new({ - 'id' => 'https://example.org/image/iiif/token', - 'profile' => described_class::IIIF_AUTHENTICATION_V1_TOKEN_PROFILE - }) - expect{inner.validate}.not_to raise_error + "id" => "https://example.org/image/iiif/token", + "profile" => described_class::IIIF_AUTHENTICATION_V1_TOKEN_PROFILE + }) + expect { inner.validate }.not_to raise_error middle = described_class.new({ "id" => "https://example.org/auth/iiif", "profile" => described_class::IIIF_AUTHENTICATION_V1_LOGIN_PROFILE, "label" => "Stanford-affiliated? Login to view", "service" => [inner] - }) - expect{middle.validate}.not_to raise_error + }) + expect { middle.validate }.not_to raise_error outer = described_class.new({ - "@type" => described_class::IIIF_IMAGE_V2_TYPE, - "@id" => "https://example.org/iiif/yy816tv6021_img_1", - "id" => "https://example.org/iiif/yy816tv6021_img_1", - "profile" => described_class::IIIF_IMAGE_V2_LEVEL1_PROFILE, - "service" => [middle] - }) - expect{outer.validate}.not_to raise_error + "@type" => described_class::IIIF_IMAGE_V2_TYPE, + "@id" => "https://example.org/iiif/yy816tv6021_img_1", + "id" => "https://example.org/iiif/yy816tv6021_img_1", + "profile" => described_class::IIIF_IMAGE_V2_LEVEL1_PROFILE, + "service" => [middle] + }) + expect { outer.validate }.not_to raise_error end end - describe 'example from http://prezi3.iiif.io/api/presentation/3.0' do - it 'iiif image v2' do + describe "example from http://prezi3.iiif.io/api/presentation/3.0" do + it "iiif image v2" do service_obj = described_class.new({ "type" => described_class::IIIF_IMAGE_V2_TYPE, "id" => "http://example.org/images/book1-page2", @@ -202,16 +201,16 @@ "profile" => "http://iiif.io/api/image/2/level1.json", "height" => 8000, "width" => 6000, - "tiles" => [{"width" => 512, "scaleFactors" => [1,2,4,8,16]}] + "tiles" => [{"width" => 512, "scaleFactors" => [1, 2, 4, 8, 16]}] }) expect(service_obj.keys.size).to eq 7 - expect(service_obj['type']).to eq described_class::IIIF_IMAGE_V2_TYPE - expect(service_obj['id']).to eq 'http://example.org/images/book1-page2' - expect(service_obj['@id']).to eq 'http://example.org/images/book1-page2' - expect(service_obj['profile']).to eq described_class::IIIF_IMAGE_V2_LEVEL1_PROFILE - expect(service_obj['height']).to eq 8000 - expect(service_obj['width']).to eq 6000 - expect(service_obj['tiles']).to eq [{"width" => 512, "scaleFactors" => [1,2,4,8,16]}] + expect(service_obj["type"]).to eq described_class::IIIF_IMAGE_V2_TYPE + expect(service_obj["id"]).to eq "http://example.org/images/book1-page2" + expect(service_obj["@id"]).to eq "http://example.org/images/book1-page2" + expect(service_obj["profile"]).to eq described_class::IIIF_IMAGE_V2_LEVEL1_PROFILE + expect(service_obj["height"]).to eq 8000 + expect(service_obj["width"]).to eq 6000 + expect(service_obj["tiles"]).to eq [{"width" => 512, "scaleFactors" => [1, 2, 4, 8, 16]}] # TODO: note that this won't validate because "height is a prohibited key in IIIF::V3::Presentation::Service" # expect{service_obj.validate}.not_to raise_error end diff --git a/spec/unit/iiif/v3/presentation/shared_examples/abstract_resource_only_keys.rb b/spec/unit/iiif/v3/presentation/shared_examples/abstract_resource_only_keys.rb index 8d4cd88..e76d8ec 100644 --- a/spec/unit/iiif/v3/presentation/shared_examples/abstract_resource_only_keys.rb +++ b/spec/unit/iiif/v3/presentation/shared_examples/abstract_resource_only_keys.rb @@ -1,7 +1,5 @@ -shared_examples 'it has the appropriate methods for abstract_resource_only_keys v3' do - +shared_examples "it has the appropriate methods for abstract_resource_only_keys v3" do described_class.new.abstract_resource_only_keys.each do |entry| - describe "#{entry[:key]}=" do it "sets #{entry[:key]}" do @ex = entry[:type].new @@ -17,11 +15,11 @@ end it "raises an exception when attempting to set it to something other than an #{entry[:type]}" do e = IIIF::V3::Presentation::IllegalValueError - expect { subject.send("#{entry[:key]}=", 'Foo') }.to raise_error e + expect { subject.send("#{entry[:key]}=", "Foo") }.to raise_error e end end - describe "#{entry[:key]}" do + describe entry[:key].to_s do it "gets #{entry[:key]}" do @ex = entry[:type].new subject[entry[:key]] = @ex @@ -31,11 +29,9 @@ it "is aliased as ##{entry[:key].camelize(:lower)}" do @ex = entry[:type].new subject[entry[:key]] = @ex - expect(subject.send("#{entry[:key].camelize(:lower)}")).to eq @ex + expect(subject.send(entry[:key].camelize(:lower).to_s)).to eq @ex end end end - end - end diff --git a/spec/unit/iiif/v3/presentation/shared_examples/any_type_keys.rb b/spec/unit/iiif/v3/presentation/shared_examples/any_type_keys.rb index ab99eee..6a29381 100644 --- a/spec/unit/iiif/v3/presentation/shared_examples/any_type_keys.rb +++ b/spec/unit/iiif/v3/presentation/shared_examples/any_type_keys.rb @@ -1,5 +1,4 @@ -shared_examples 'it has the appropriate methods for any-type keys v3' do - +shared_examples "it has the appropriate methods for any-type keys v3" do described_class.new.any_type_keys.each do |prop| describe "##{prop}=" do it "sets self['#{prop}']" do @@ -16,16 +15,15 @@ describe "##{prop}" do it "gets self[#{prop}]" do - subject.send("[]=", prop, fixed_values[prop]) - expect(subject.send("#{prop}")).to eq fixed_values[prop] + subject.send(:[]=, prop, fixed_values[prop]) + expect(subject.send(prop.to_s)).to eq fixed_values[prop] end if prop.camelize(:lower) != prop it "is aliased as ##{prop.camelize(:lower)}" do - subject.send("[]=", prop, fixed_values[prop]) - expect(subject.send("#{prop.camelize(:lower)}")).to eq fixed_values[prop] + subject.send(:[]=, prop, fixed_values[prop]) + expect(subject.send(prop.camelize(:lower).to_s)).to eq fixed_values[prop] end end end end - end diff --git a/spec/unit/iiif/v3/presentation/shared_examples/array_only_keys.rb b/spec/unit/iiif/v3/presentation/shared_examples/array_only_keys.rb index 5ef0160..6fe6978 100644 --- a/spec/unit/iiif/v3/presentation/shared_examples/array_only_keys.rb +++ b/spec/unit/iiif/v3/presentation/shared_examples/array_only_keys.rb @@ -1,40 +1,36 @@ -shared_examples 'it has the appropriate methods for array-only keys v3' do - +shared_examples "it has the appropriate methods for array-only keys v3" do described_class.new.array_only_keys.each do |prop| - describe "#{prop}=" do it "sets #{prop}" do - ex = [{'label' => 'XYZ'}] + ex = [{"label" => "XYZ"}] subject.send("#{prop}=", ex) expect(subject[prop]).to eq ex end if prop.camelize(:lower) != prop it "is aliased as ##{prop.camelize(:lower)}=" do - ex = [{'label' => 'XYZ'}] + ex = [{"label" => "XYZ"}] subject.send("#{prop.camelize(:lower)}=", ex) expect(subject[prop]).to eq ex end end - it 'raises an exception when attempting to set it to something other than an Array' do - expect { subject.send("#{prop}=", 'Foo') }.to raise_error IIIF::V3::Presentation::IllegalValueError + it "raises an exception when attempting to set it to something other than an Array" do + expect { subject.send("#{prop}=", "Foo") }.to raise_error IIIF::V3::Presentation::IllegalValueError end end - describe "#{prop}" do + describe prop.to_s do it "gets #{prop}" do - ex = [{'label' => 'XYZ'}] + ex = [{"label" => "XYZ"}] subject[prop] = ex expect(subject.send(prop)).to eq ex end if prop.camelize(:lower) != prop it "is aliased as ##{prop.camelize(:lower)}" do - ex = [{'label' => 'XYZ'}] + ex = [{"label" => "XYZ"}] subject[prop] = ex - expect(subject.send("#{prop.camelize(:lower)}")).to eq ex + expect(subject.send(prop.camelize(:lower).to_s)).to eq ex end end end - end - end diff --git a/spec/unit/iiif/v3/presentation/shared_examples/hash_only_keys.rb b/spec/unit/iiif/v3/presentation/shared_examples/hash_only_keys.rb index b4c16a7..6ccaa6b 100644 --- a/spec/unit/iiif/v3/presentation/shared_examples/hash_only_keys.rb +++ b/spec/unit/iiif/v3/presentation/shared_examples/hash_only_keys.rb @@ -1,40 +1,36 @@ -shared_examples 'it has the appropriate methods for hash-only keys v3' do - +shared_examples "it has the appropriate methods for hash-only keys v3" do described_class.new.hash_only_keys.each do |prop| - describe "#{prop}=" do it "sets #{prop}" do - ex = {'label' => 'XYZ', 'fooBar' => 'bar'} + ex = {"label" => "XYZ", "fooBar" => "bar"} subject.send("#{prop}=", ex) expect(subject[prop]).to eq ex end if prop.camelize(:lower) != prop it "is aliased as ##{prop.camelize(:lower)}=" do - ex = {'label' => 'XYZ'} + ex = {"label" => "XYZ"} subject.send("#{prop.camelize(:lower)}=", ex) expect(subject[prop]).to eq ex end end - it 'raises an exception when attempting to set it to something other than a Hash' do - expect { subject.send("#{prop}=", ['Foo']) }.to raise_error IIIF::V3::Presentation::IllegalValueError + it "raises an exception when attempting to set it to something other than a Hash" do + expect { subject.send("#{prop}=", ["Foo"]) }.to raise_error IIIF::V3::Presentation::IllegalValueError end end - describe "#{prop}" do + describe prop.to_s do it "gets #{prop}" do - ex = {'label' => 'XYZ', 'fooBar' => 'bar'} + ex = {"label" => "XYZ", "fooBar" => "bar"} subject[prop] = ex expect(subject.send(prop)).to eq ex end if prop.camelize(:lower) != prop it "is aliased as ##{prop.camelize(:lower)}" do - ex = {'fooBar' => 'bar'} + ex = {"fooBar" => "bar"} subject[prop] = ex - expect(subject.send("#{prop.camelize(:lower)}")).to eq ex + expect(subject.send(prop.camelize(:lower).to_s)).to eq ex end end end - end - end diff --git a/spec/unit/iiif/v3/presentation/shared_examples/int_only_keys.rb b/spec/unit/iiif/v3/presentation/shared_examples/int_only_keys.rb index 5f4a9ae..2e1af6c 100644 --- a/spec/unit/iiif/v3/presentation/shared_examples/int_only_keys.rb +++ b/spec/unit/iiif/v3/presentation/shared_examples/int_only_keys.rb @@ -1,7 +1,5 @@ -shared_examples 'it has the appropriate methods for integer-only keys v3' do - +shared_examples "it has the appropriate methods for integer-only keys v3" do described_class.new.int_only_keys.each do |prop| - describe "#{prop}=" do before(:all) do @ex = 7200 @@ -16,15 +14,15 @@ expect(subject[prop]).to eq @ex end end - it 'raises an exception when attempting to set it to something other than an Integer' do - expect { subject.send("#{prop}=", 'Foo') }.to raise_error IIIF::V3::Presentation::IllegalValueError + it "raises an exception when attempting to set it to something other than an Integer" do + expect { subject.send("#{prop}=", "Foo") }.to raise_error IIIF::V3::Presentation::IllegalValueError end - it 'raises an exception when attempting to set it to a negative number' do + it "raises an exception when attempting to set it to a negative number" do expect { subject.send("#{prop}=", -1) }.to raise_error IIIF::V3::Presentation::IllegalValueError end end - describe "#{prop}" do + describe prop.to_s do before(:all) do @ex = 7200 end @@ -35,11 +33,9 @@ if prop.camelize(:lower) != prop it "is aliased as ##{prop.camelize(:lower)}" do subject[prop] = @ex - expect(subject.send("#{prop.camelize(:lower)}")).to eq @ex + expect(subject.send(prop.camelize(:lower).to_s)).to eq @ex end end end - end - end diff --git a/spec/unit/iiif/v3/presentation/shared_examples/numeric_only_keys.rb b/spec/unit/iiif/v3/presentation/shared_examples/numeric_only_keys.rb index a0e27b3..a1de9f4 100644 --- a/spec/unit/iiif/v3/presentation/shared_examples/numeric_only_keys.rb +++ b/spec/unit/iiif/v3/presentation/shared_examples/numeric_only_keys.rb @@ -1,7 +1,5 @@ -shared_examples 'it has the appropriate methods for numeric-only keys v3' do - +shared_examples "it has the appropriate methods for numeric-only keys v3" do described_class.new.numeric_only_keys.each do |prop| - describe "#{prop}=" do before(:all) do @ex = 7200.0 @@ -16,15 +14,15 @@ expect(subject[prop]).to eq @ex end end - it 'raises an exception when attempting to set it to something other than an Integer' do - expect { subject.send("#{prop}=", 'Foo') }.to raise_error IIIF::V3::Presentation::IllegalValueError + it "raises an exception when attempting to set it to something other than an Integer" do + expect { subject.send("#{prop}=", "Foo") }.to raise_error IIIF::V3::Presentation::IllegalValueError end - it 'raises an exception when attempting to set it to a negative number' do + it "raises an exception when attempting to set it to a negative number" do expect { subject.send("#{prop}=", -1.0) }.to raise_error IIIF::V3::Presentation::IllegalValueError end end - describe "#{prop}" do + describe prop.to_s do before(:all) do @ex = 7200.0 end @@ -35,11 +33,9 @@ if prop.camelize(:lower) != prop it "is aliased as ##{prop.camelize(:lower)}" do subject[prop] = @ex - expect(subject.send("#{prop.camelize(:lower)}")).to eq @ex + expect(subject.send(prop.camelize(:lower).to_s)).to eq @ex end end end - end - end diff --git a/spec/unit/iiif/v3/presentation/shared_examples/string_only_keys.rb b/spec/unit/iiif/v3/presentation/shared_examples/string_only_keys.rb index 0e819b3..dd18884 100644 --- a/spec/unit/iiif/v3/presentation/shared_examples/string_only_keys.rb +++ b/spec/unit/iiif/v3/presentation/shared_examples/string_only_keys.rb @@ -1,26 +1,22 @@ -shared_examples 'it has the appropriate methods for string-only keys v3' do - +shared_examples "it has the appropriate methods for string-only keys v3" do described_class.new.string_only_keys.each do |prop| - describe "#{prop}=" do it "sets #{prop}" do - ex = 'foo' + ex = "foo" subject.send("#{prop}=", ex) expect(subject[prop]).to eq ex end - it 'raises an exception when attempting to set it to something other than a String' do - expect { subject.send("#{prop}=", ['Foo']) }.to raise_error IIIF::V3::Presentation::IllegalValueError + it "raises an exception when attempting to set it to something other than a String" do + expect { subject.send("#{prop}=", ["Foo"]) }.to raise_error IIIF::V3::Presentation::IllegalValueError end end - describe "#{prop}" do + describe prop.to_s do it "gets #{prop}" do - ex = 'bar' + ex = "bar" subject[prop] = ex expect(subject.send(prop)).to eq ex end end - end - end diff --git a/spec/unit/iiif/v3/presentation/shared_examples/uri_only_keys.rb b/spec/unit/iiif/v3/presentation/shared_examples/uri_only_keys.rb index 270081c..9ad73a8 100644 --- a/spec/unit/iiif/v3/presentation/shared_examples/uri_only_keys.rb +++ b/spec/unit/iiif/v3/presentation/shared_examples/uri_only_keys.rb @@ -1,31 +1,27 @@ -shared_examples 'it has the appropriate methods for uri-only keys v3' do - +shared_examples "it has the appropriate methods for uri-only keys v3" do described_class.new.uri_only_keys.each do |prop| - describe "#{prop}=" do it "sets #{prop}" do - ex = 'http://example.org/foo' + ex = "http://example.org/foo" subject.send("#{prop}=", ex) expect(subject[prop]).to eq ex end - it 'raises an exception when attempting to set it to something other than a String' do - expect { subject.send("#{prop}=", ['Foo']) }.to raise_error IIIF::V3::Presentation::IllegalValueError + it "raises an exception when attempting to set it to something other than a String" do + expect { subject.send("#{prop}=", ["Foo"]) }.to raise_error IIIF::V3::Presentation::IllegalValueError expect { subject.send("#{prop}=", nil) }.to raise_error IIIF::V3::Presentation::IllegalValueError end - it 'raises an exception when attempting to set it to something other than a parseable URI' do - expect { subject.send("#{prop}=", 'Not a URI') }.to raise_error IIIF::V3::Presentation::IllegalValueError - expect { subject.send("#{prop}=", '') }.to raise_error IIIF::V3::Presentation::IllegalValueError + it "raises an exception when attempting to set it to something other than a parseable URI" do + expect { subject.send("#{prop}=", "Not a URI") }.to raise_error IIIF::V3::Presentation::IllegalValueError + expect { subject.send("#{prop}=", "") }.to raise_error IIIF::V3::Presentation::IllegalValueError end end - describe "#{prop}" do + describe prop.to_s do it "gets #{prop}" do - ex = 'bar' + ex = "bar" subject[prop] = ex expect(subject.send(prop)).to eq ex end end - end - end