diff options
author | Austin Ziegler <austin@zieglers.ca> | 2021-06-02 10:42:23 -0400 |
---|---|---|
committer | GitHub <noreply@github.com> | 2021-06-02 10:42:23 -0400 |
commit | 6c8324d2396e7698296bbecf376a4a647b258057 (patch) | |
tree | 8310377885377e1f44526f69c8588c759b3aa215 | |
parent | b8db65ac00b8f23d4274ed47aada475a65cc24d0 (diff) | |
download | mime-types-6c8324d2396e7698296bbecf376a4a647b258057.tar.gz |
Convert to standardrb (#156)
- I mostly don’t care about this, but there are a couple of things that
Standard does that I disagree with. They are inherited from Rubocop,
but Standard fixes many of Rubocop’s nonsense rules.
- Array literal wrappers %i[], %w[], etc. are just ugly and never
should have become any sort of standard. I would be happier if this
part of standard were just completely disabled, because it‘s
unnecessary and wrong.
- Quote literals having to be %q() is equally wrong. I’ve avoided the
issue here because the generated gemspec uses both "unnecessary"
quote literals (it’s necessary if I say it’s necessary) and the
wrong wrappers (I wouldn’t use %q<>, but this is generated code).
- I still think that short hashes can be `{ foo: "bar" }`, but I’m
mostly using Elixir these days, so I don’t mind `%{foo: "bar"}`, so
I can get used to it in Ruby. It still feels wrong, almost 20 years
in.
- There are semantic differences between and / &&, or / ||, but in some
cases the reformatted code is substantially _worse_ to read. Again,
I mostly don’t _care_ about this difference, but Rubocop’s insistence
is silly; these should only be replaced where there _is_ ambiguity.
- Replacing `x = foo or next` should never be replaced with `(x = foo)
|| next`. That’s replacing something that is somewhat readable with
something damned-near unreadable. Both should be replaced with:
```ruby
x = foo
next unless x
```
- YAML.safe_load works differently between Psych 2.x and Psych 3.x, so
some updates have been made to make that work cleanly.
Overall, this introduces a lot of churn, but I think will be easier to
deal with updates to `standardrb` instead of the rapid churn that has
been Rubocop.
31 files changed, 825 insertions, 911 deletions
@@ -13,3 +13,4 @@ publish test/cache.tst tmp/ .byebug_history +tags diff --git a/.rubocop.yml b/.rubocop.yml deleted file mode 100644 index 0051519..0000000 --- a/.rubocop.yml +++ /dev/null @@ -1,94 +0,0 @@ ---- -AllCops: - DisplayCopNames: true - DisplayStyleGuide: true - ExtraDetails: true - Exclude: - - mime-types.gemspec - -Layout/ParameterAlignment: - EnforcedStyle: with_fixed_indentation - -Layout/DotPosition: - EnforcedStyle: trailing - -Layout/MultilineMethodCallIndentation: - EnforcedStyle: indented - -Layout/LineLength: - Max: 100 - -Naming/FileName: - Exclude: - - lib/mime-types.rb - -Naming/MemoizedInstanceVariableName: - Exclude: - - lib/mime/types/registry.rb - -Naming/MethodParameterName: - Exclude: - - lib/mime/types/logger.rb - -Naming/VariableNumber: - Exclude: - - lib/mime/types/logger.rb - -#Performance/Caller: -# Exclude: -# - lib/mime/types/deprecations.rb -# -Security/MarshalLoad: - Exclude: - - lib/mime/types/cache.rb - - test/test_mime_types_cache.rb - -Security/YAMLLoad: - Exclude: - - lib/mime/types/loader.rb - -Style/BlockDelimiters: - EnforcedStyle: semantic - ProceduralMethods: - - trace - - assert_raises - - spec - FunctionalMethods: - - let - -Style/PercentLiteralDelimiters: - PreferredDelimiters: - default: () - '%i': '()' - '%I': '()' - '%r': '{}' - '%w': '()' - '%W': '()' - -Style/RescueStandardError: - EnforcedStyle: implicit - -Style/SignalException: - EnforcedStyle: semantic - -Layout/HeredocIndentation: { Enabled: false } -Metrics/AbcSize: { Enabled: false } -Metrics/BlockLength: { Enabled: false } -Metrics/ClassLength: { Enabled: false } -Metrics/CyclomaticComplexity: { Enabled: false } -Metrics/MethodLength: { Enabled: false} -Metrics/PerceivedComplexity: { Enabled: false } -Style/AndOr: { Enabled: false } -Style/AsciiComments: { Enabled: false } -Style/ClassAndModuleChildren: { Enabled: false } -Style/ClassCheck: { Enabled: false } -Style/CommentedKeyword: { Enabled: false } -Style/DoubleNegation: { Enabled: false } -Style/EmptyMethod: { Enabled: false } -Style/ExpandPathArguments: { Enabled: false } -Style/FormatString: { Enabled: false } -Style/FormatStringToken: { Enabled: false } -Style/MultilineBlockChain: { Enabled: false } -Style/SafeNavigation: { Enabled: false } -Style/WordArray: { Enabled: false } -Style/SymbolArray: { Enabled: false } diff --git a/.standard.yml b/.standard.yml new file mode 100644 index 0000000..8ae76a7 --- /dev/null +++ b/.standard.yml @@ -0,0 +1,4 @@ +parallel: true +ruby_version: 2.0 +ignore: + - 'mime-types.gemspec' @@ -3,9 +3,9 @@ # NOTE: This file is present to keep Travis CI happy. Edits to it will not # be accepted. -source 'https://rubygems.org/' +source "https://rubygems.org/" -gem 'mime-types-data', path: '../mime-types-data' if ENV['DEV'] +gem "mime-types-data", path: "../mime-types-data" if ENV["DEV"] gemspec @@ -15,6 +15,7 @@ [#150]. Removed Coveralls configuration. - Igor Victor added TruffleRuby to the Travis CI configuration [#149]. - Koichi ITO loosened an excessively tight dependency [#147]. + - Started using `standardrb` for Ruby formatting and validation. ## 3.3.1 / 2019-12-26 @@ -28,8 +29,7 @@ - Administrivia: - - Olle Jonsson removed an outdated Travis configuration option (`sudo: - false`). [#142] + - Olle Jonsson removed an outdated Travis configuration option (`sudo: false`). [#142] ## 3.3 / 2019-09-04 @@ -64,8 +64,7 @@ to be in the same family even if strict sorting would cause an unregistered type to be sorted first. [#132] - - Dillon Welch contributed a change that added `frozen_string_literal: - true` to files so that modern Rubies can automatically reduce duplicate + - Dillon Welch contributed a change that added `frozen_string_literal: true` to files so that modern Rubies can automatically reduce duplicate string allocations. [#135] - 2 bug fixes @@ -169,8 +168,7 @@ `x-` prefixes. - Improved initialization with an Array works so that extensions do not - need to be wrapped in another array. This means that `%w(text/yaml yaml - yml)` works in the same way that `['text/yaml', %w(yaml yml)]` did (and + need to be wrapped in another array. This means that `%w(text/yaml yaml yml)` works in the same way that `['text/yaml', %w(yaml yml)]` did (and still does). - Changed `priority_compare` to conform with attributes that no longer @@ -1,72 +1,74 @@ # frozen_string_literal: true -require 'rubygems' -require 'hoe' -require 'rake/clean' +require "rubygems" +require "hoe" +require "rake/clean" Hoe.plugin :doofus Hoe.plugin :gemspec2 Hoe.plugin :git Hoe.plugin :minitest -Hoe.plugin :email unless ENV['CI'] +Hoe.plugin :email unless ENV["CI"] -spec = Hoe.spec 'mime-types' do - developer('Austin Ziegler', 'halostatue@gmail.com') +spec = Hoe.spec "mime-types" do + developer("Austin Ziegler", "halostatue@gmail.com") self.need_tar = true - require_ruby_version '>= 2.0' + require_ruby_version ">= 2.0" - self.history_file = 'History.md' - self.readme_file = 'README.rdoc' + self.history_file = "History.md" + self.readme_file = "README.rdoc" - license 'MIT' + license "MIT" - extra_deps << ['mime-types-data', '~> 3.2015'] + extra_deps << ["mime-types-data", "~> 3.2015"] - extra_dev_deps << ['hoe-doofus', '~> 1.0'] - extra_dev_deps << ['hoe-gemspec2', '~> 1.1'] - extra_dev_deps << ['hoe-git', '~> 1.6'] - extra_dev_deps << ['hoe-rubygems', '~> 1.0'] - extra_dev_deps << ['minitest', '~> 5.4'] - extra_dev_deps << ['minitest-autotest', '~> 1.0'] - extra_dev_deps << ['minitest-focus', '~> 1.0'] - extra_dev_deps << ['minitest-bonus-assertions', '~> 3.0'] - extra_dev_deps << ['minitest-hooks', '~> 1.4'] - extra_dev_deps << ['rake', '>= 10.0', '< 14.0'] + extra_dev_deps << ["hoe-doofus", "~> 1.0"] + extra_dev_deps << ["hoe-gemspec2", "~> 1.1"] + extra_dev_deps << ["hoe-git", "~> 1.6"] + extra_dev_deps << ["hoe-rubygems", "~> 1.0"] + extra_dev_deps << ["standard", "~> 1.0"] + extra_dev_deps << ["minitest", "~> 5.4"] + extra_dev_deps << ["minitest-autotest", "~> 1.0"] + extra_dev_deps << ["minitest-focus", "~> 1.0"] + extra_dev_deps << ["minitest-bonus-assertions", "~> 3.0"] + extra_dev_deps << ["minitest-hooks", "~> 1.4"] + extra_dev_deps << ["rake", ">= 10.0", "< 14.0"] + extra_dev_deps << ["psych", "~> 3.0"] - if Gem::Version.new(RUBY_VERSION) >= Gem::Version.new('2.0') - extra_dev_deps << ['simplecov', '~> 0.7'] + if Gem::Version.new(RUBY_VERSION) >= Gem::Version.new("2.0") + extra_dev_deps << ["simplecov", "~> 0.7"] end end namespace :benchmark do task :support do - %w(lib support).each { |path| + %w[lib support].each { |path| $LOAD_PATH.unshift(File.join(Rake.application.original_dir, path)) } end - desc 'Benchmark Load Times' - task :load, [:repeats] => 'benchmark:support' do |_, args| - require 'benchmarks/load' + desc "Benchmark Load Times" + task :load, [:repeats] => "benchmark:support" do |_, args| + require "benchmarks/load" Benchmarks::Load.report( - File.join(Rake.application.original_dir, 'lib'), + File.join(Rake.application.original_dir, "lib"), args.repeats ) end - desc 'Allocation counts' - task :allocations, [:top_x, :mime_types_only] => 'benchmark:support' do |_, args| - require 'benchmarks/load_allocations' + desc "Allocation counts" + task :allocations, [:top_x, :mime_types_only] => "benchmark:support" do |_, args| + require "benchmarks/load_allocations" Benchmarks::LoadAllocations.report( top_x: args.top_x, mime_types_only: args.mime_types_only ) end - desc 'Columnar allocation counts' - task 'allocations:columnar', [:top_x, :mime_types_only] => 'benchmark:support' do |_, args| - require 'benchmarks/load_allocations' + desc "Columnar allocation counts" + task "allocations:columnar", [:top_x, :mime_types_only] => "benchmark:support" do |_, args| + require "benchmarks/load_allocations" Benchmarks::LoadAllocations.report( columnar: true, top_x: args.top_x, @@ -74,9 +76,9 @@ namespace :benchmark do ) end - desc 'Columnar allocation counts (full load)' - task 'allocations:columnar:full', [:top_x, :mime_types_only] => 'benchmark:support' do |_, args| - require 'benchmarks/load_allocations' + desc "Columnar allocation counts (full load)" + task "allocations:columnar:full", [:top_x, :mime_types_only] => "benchmark:support" do |_, args| + require "benchmarks/load_allocations" Benchmarks::LoadAllocations.report( columnar: true, top_x: args.top_x, @@ -85,18 +87,18 @@ namespace :benchmark do ) end - desc 'Memory profiler' - task :memory, [:top_x, :mime_types_only] => 'benchmark:support' do |_, args| - require 'benchmarks/memory_profiler' + desc "Memory profiler" + task :memory, [:top_x, :mime_types_only] => "benchmark:support" do |_, args| + require "benchmarks/memory_profiler" Benchmarks::ProfileMemory.report( mime_types_only: args.mime_types_only, top_x: args.top_x ) end - desc 'Columnar memory profiler' - task 'memory:columnar', [:top_x, :mime_types_only] => 'benchmark:support' do |_, args| - require 'benchmarks/memory_profiler' + desc "Columnar memory profiler" + task "memory:columnar", [:top_x, :mime_types_only] => "benchmark:support" do |_, args| + require "benchmarks/memory_profiler" Benchmarks::ProfileMemory.report( columnar: true, mime_types_only: args.mime_types_only, @@ -104,9 +106,9 @@ namespace :benchmark do ) end - desc 'Columnar allocation counts (full load)' - task 'memory:columnar:full', [:top_x, :mime_types_only] => 'benchmark:support' do |_, args| - require 'benchmarks/memory_profiler' + desc "Columnar allocation counts (full load)" + task "memory:columnar:full", [:top_x, :mime_types_only] => "benchmark:support" do |_, args| + require "benchmarks/memory_profiler" Benchmarks::ProfileMemory.report( columnar: true, full: true, @@ -115,72 +117,72 @@ namespace :benchmark do ) end - desc 'Object counts' - task objects: 'benchmark:support' do - require 'benchmarks/object_counts' + desc "Object counts" + task objects: "benchmark:support" do + require "benchmarks/object_counts" Benchmarks::ObjectCounts.report end - desc 'Columnar object counts' - task 'objects:columnar' => 'benchmark:support' do - require 'benchmarks/object_counts' + desc "Columnar object counts" + task "objects:columnar" => "benchmark:support" do + require "benchmarks/object_counts" Benchmarks::ObjectCounts.report(columnar: true) end - desc 'Columnar object counts (full load)' - task 'objects:columnar:full' => 'benchmark:support' do - require 'benchmarks/object_counts' + desc "Columnar object counts (full load)" + task "objects:columnar:full" => "benchmark:support" do + require "benchmarks/object_counts" Benchmarks::ObjectCounts.report(columnar: true, full: true) end end namespace :profile do - directory 'tmp/profile' + directory "tmp/profile" - CLEAN.add 'tmp' + CLEAN.add "tmp" def ruby_prof(script) - require 'pathname' - output = Pathname('tmp/profile').join(script) + require "pathname" + output = Pathname("tmp/profile").join(script) output.mkpath - script = Pathname('support/profile').join("#{script}.rb") + script = Pathname("support/profile").join("#{script}.rb") args = [ - '-W0', - '-Ilib', - '-S', 'ruby-prof', - '-R', 'mime/types', - '-s', 'self', - '-p', 'multi', - '-f', output.to_s, + "-W0", + "-Ilib", + "-S", "ruby-prof", + "-R", "mime/types", + "-s", "self", + "-p", "multi", + "-f", output.to_s, script.to_s ] - ruby args.join(' ') + ruby args.join(" ") end - task full: 'tmp/profile' do - ruby_prof 'full' + task full: "tmp/profile" do + ruby_prof "full" end task columnar: :support do - ruby_prof 'columnar' + ruby_prof "columnar" end - task 'columnar:full' => :support do - ruby_prof 'columnar_full' + task "columnar:full" => :support do + ruby_prof "columnar_full" end end -if Gem::Version.new(RUBY_VERSION) >= Gem::Version.new('2.0') +if Gem::Version.new(RUBY_VERSION) >= Gem::Version.new("2.0") namespace :test do - desc 'Run test coverage' + desc "Run test coverage" task :coverage do spec.test_prelude = [ 'require "simplecov"', 'SimpleCov.start("test_frameworks") { command_name "Minitest" }', 'gem "minitest"' - ].join('; ') - Rake::Task['test'].execute + ].join("; ") + Rake::Task["test"].execute end end end @@ -188,18 +190,18 @@ end namespace :convert do namespace :docs do task :setup do - gem 'rdoc' - require 'rdoc/rdoc' + gem "rdoc" + require "rdoc/rdoc" @doc_converter ||= RDoc::Markup::ToMarkdown.new end - FileList['*.rdoc'].each do |name| + FileList["*.rdoc"].each do |name| rdoc = name - mark = "#{File.basename(name, '.rdoc')}.md" + mark = "#{File.basename(name, ".rdoc")}.md" file mark => [rdoc, :setup] do |t| puts "#{rdoc} => #{mark}" - File.open(t.name, 'wb') { |target| + File.open(t.name, "wb") { |target| target.write @doc_converter.convert(IO.read(t.prerequisites.first)) } end @@ -210,30 +212,30 @@ namespace :convert do end end - desc 'Convert documentation from RDoc to Markdown' - task docs: 'convert:docs:run' + desc "Convert documentation from RDoc to Markdown" + task docs: "convert:docs:run" end -task 'deps:top', [:number] do |_, args| - require 'net/http' - require 'json' +task "deps:top", [:number] do |_, args| + require "net/http" + require "json" - def rubygems_get(gem_name: '', endpoint: '') - path = File.join('/api/v1/gems/', gem_name, endpoint).chomp('/') + '.json' - Net::HTTP.start('rubygems.org', use_ssl: true) do |http| + def rubygems_get(gem_name: "", endpoint: "") + path = File.join("/api/v1/gems/", gem_name, endpoint).chomp("/") + ".json" + Net::HTTP.start("rubygems.org", use_ssl: true) do |http| JSON.parse(http.get(path).body) end end results = rubygems_get( - gem_name: 'mime-types', - endpoint: 'reverse_dependencies' + gem_name: "mime-types", + endpoint: "reverse_dependencies" ) weighted_results = {} results.each do |name| begin - weighted_results[name] = rubygems_get(gem_name: name)['downloads'] + weighted_results[name] = rubygems_get(gem_name: name)["downloads"] rescue => e puts "#{name} #{e.message}" end @@ -247,9 +249,9 @@ task 'deps:top', [:number] do |_, args| end task :console do - arguments = %w(pry) + arguments = %w[pry] arguments.push(*spec.spec.require_paths.map { |dir| "-I#{dir}" }) - arguments.push("-r#{spec.spec.name.gsub('-', File::SEPARATOR)}") + arguments.push("-r#{spec.spec.name.gsub("-", File::SEPARATOR)}") unless system(*arguments) error "Command failed: #{show_command}" abort diff --git a/lib/mime-types.rb b/lib/mime-types.rb index 5c7dd73..dcb87cf 100644 --- a/lib/mime-types.rb +++ b/lib/mime-types.rb @@ -1,3 +1,3 @@ # frozen_string_literal: true -require 'mime/types' +require "mime/types" diff --git a/lib/mime/type.rb b/lib/mime/type.rb index 9035a73..cdf2471 100644 --- a/lib/mime/type.rb +++ b/lib/mime/type.rb @@ -92,21 +92,21 @@ class MIME::Type end # The released version of the mime-types library. - VERSION = '3.3.1' + VERSION = "3.3.1" include Comparable # :stopdoc: # TODO verify mime-type character restrictions; I am pretty sure that this is # too wide open. - MEDIA_TYPE_RE = %r{([-\w.+]+)/([-\w.+]*)}.freeze - I18N_RE = /[^[:alnum:]]/.freeze - BINARY_ENCODINGS = %w(base64 8bit).freeze - ASCII_ENCODINGS = %w(7bit quoted-printable).freeze + MEDIA_TYPE_RE = %r{([-\w.+]+)/([-\w.+]*)}.freeze + I18N_RE = /[^[:alnum:]]/.freeze + BINARY_ENCODINGS = %w[base64 8bit].freeze + ASCII_ENCODINGS = %w[7bit quoted-printable].freeze # :startdoc: private_constant :MEDIA_TYPE_RE, :I18N_RE, :BINARY_ENCODINGS, - :ASCII_ENCODINGS + :ASCII_ENCODINGS # Builds a MIME::Type object from the +content_type+, a MIME Content Type # value (e.g., 'text/plain' or 'application/x-eruby'). The constructed object @@ -121,7 +121,7 @@ class MIME::Type # * Otherwise, the content_type will be used as a string. # # Yields the newly constructed +self+ object. - def initialize(content_type) # :yields self: + def initialize(content_type) # :yields: self @friendly = {} @obsolete = @registered = false @preferred_extension = @docs = @use_instead = nil @@ -148,11 +148,12 @@ class MIME::Type # Indicates that a MIME type is like another type. This differs from # <tt>==</tt> because <tt>x-</tt> prefixes are removed for this comparison. def like?(other) - other = if other.respond_to?(:simplified) - MIME::Type.simplified(other.simplified, remove_x_prefix: true) - else - MIME::Type.simplified(other.to_s, remove_x_prefix: true) - end + other = + if other.respond_to?(:simplified) + MIME::Type.simplified(other.simplified, remove_x_prefix: true) + else + MIME::Type.simplified(other.to_s, remove_x_prefix: true) + end MIME::Type.simplified(simplified, remove_x_prefix: true) == other end @@ -166,8 +167,8 @@ class MIME::Type elsif other.respond_to?(:simplified) simplified <=> other.simplified else - filtered = 'silent' if other == :silent - filtered ||= 'true' if other == true + filtered = "silent" if other == :silent + filtered ||= "true" if other == true filtered ||= other.to_s simplified <=> MIME::Type.simplified(filtered) @@ -193,23 +194,24 @@ class MIME::Type def priority_compare(other) pc = simplified <=> other.simplified if pc.zero? || !(extensions & other.extensions).empty? - pc = if (reg = registered?) != other.registered? - reg ? -1 : 1 # registered < unregistered - elsif (comp = complete?) != other.complete? - comp ? -1 : 1 # complete < incomplete - elsif (obs = obsolete?) != other.obsolete? - obs ? 1 : -1 # current < obsolete - elsif obs and ((ui = use_instead) != (oui = other.use_instead)) - if ui.nil? - 1 - elsif oui.nil? - -1 - else - ui <=> oui - end - else - 0 - end + pc = + if (reg = registered?) != other.registered? + reg ? -1 : 1 # registered < unregistered + elsif (comp = complete?) != other.complete? + comp ? -1 : 1 # complete < incomplete + elsif (obs = obsolete?) != other.obsolete? + obs ? 1 : -1 # current < obsolete + elsif obs && ((ui = use_instead) != (oui = other.use_instead)) + if ui.nil? + 1 + elsif oui.nil? + -1 + else + ui <=> oui + end + else + 0 + end end pc @@ -218,7 +220,7 @@ class MIME::Type # Returns +true+ if the +other+ object is a MIME::Type and the content types # match. def eql?(other) - other.kind_of?(MIME::Type) and self == other + other.is_a?(MIME::Type) && (self == other) end # Returns the whole MIME content-type string. @@ -324,9 +326,9 @@ class MIME::Type ## def encoding=(enc) # :nodoc: - if enc.nil? or enc == :default + if enc.nil? || (enc == :default) @encoding = default_encoding - elsif BINARY_ENCODINGS.include?(enc) or ASCII_ENCODINGS.include?(enc) + elsif BINARY_ENCODINGS.include?(enc) || ASCII_ENCODINGS.include?(enc) @encoding = enc else fail InvalidEncoding, enc @@ -335,7 +337,7 @@ class MIME::Type # Returns the default encoding for the MIME::Type based on the media type. def default_encoding - @media_type == 'text' ? 'quoted-printable' : 'base64' + @media_type == "text" ? "quoted-printable" : "base64" end ## @@ -355,7 +357,7 @@ class MIME::Type # Returns +true+ if the media type is obsolete. attr_accessor :obsolete - alias obsolete? obsolete + alias_method :obsolete?, :obsolete # The documentation for this MIME::Type. attr_accessor :docs @@ -365,7 +367,7 @@ class MIME::Type # call-seq: # text_plain.friendly # => "Text File" # text_plain.friendly('en') # => "Text File" - def friendly(lang = 'en') + def friendly(lang = "en") @friendly ||= {} case lang @@ -377,7 +379,7 @@ class MIME::Type @friendly.update(lang) else fail ArgumentError, - "Expected a language or translation set, not #{lang.inspect}" + "Expected a language or translation set, not #{lang.inspect}" end end @@ -408,14 +410,14 @@ class MIME::Type # The decoded cross-reference URL list for this MIME::Type. def xref_urls xrefs.flat_map { |type, values| - name = :"xref_url_for_#{type.tr('-', '_')}" - respond_to?(name, true) and xref_map(values, name) or values.to_a + name = :"xref_url_for_#{type.tr("-", "_")}" + respond_to?(name, true) && xref_map(values, name) || values.to_a } end # Indicates whether the MIME type has been registered with IANA. attr_accessor :registered - alias registered? registered + alias_method :registered?, :registered # MIME types can be specified to be sent across a network in particular # formats. This method returns +true+ when the MIME::Type encoding is set @@ -433,7 +435,7 @@ class MIME::Type # Indicateswhether the MIME type is declared as a signature type. attr_accessor :signature - alias signature? signature + alias_method :signature?, :signature # Returns +true+ if the MIME::Type specifies an extension list, # indicating that it is a complete MIME::Type. @@ -456,7 +458,7 @@ class MIME::Type # Converts the MIME::Type to a JSON string. def to_json(*args) - require 'json' + require "json" to_h.to_json(*args) end @@ -472,26 +474,26 @@ class MIME::Type # # This method should be considered a private implementation detail. def encode_with(coder) - coder['content-type'] = @content_type - coder['docs'] = @docs unless @docs.nil? or @docs.empty? - coder['friendly'] = @friendly unless @friendly.nil? or @friendly.empty? - coder['encoding'] = @encoding - coder['extensions'] = @extensions.to_a unless @extensions.empty? - coder['preferred-extension'] = @preferred_extension if @preferred_extension + coder["content-type"] = @content_type + coder["docs"] = @docs unless @docs.nil? || @docs.empty? + coder["friendly"] = @friendly unless @friendly.nil? || @friendly.empty? + coder["encoding"] = @encoding + coder["extensions"] = @extensions.to_a unless @extensions.empty? + coder["preferred-extension"] = @preferred_extension if @preferred_extension if obsolete? - coder['obsolete'] = obsolete? - coder['use-instead'] = use_instead if use_instead + coder["obsolete"] = obsolete? + coder["use-instead"] = use_instead if use_instead end unless xrefs.empty? {}.tap do |hash| xrefs.each do |k, v| hash[k] = v.to_a.sort end - coder['xrefs'] = hash + coder["xrefs"] = hash end end - coder['registered'] = registered? - coder['signature'] = signature? if signature? + coder["registered"] = registered? + coder["signature"] = signature? if signature? coder end @@ -500,18 +502,18 @@ class MIME::Type # # This method should be considered a private implementation detail. def init_with(coder) - self.content_type = coder['content-type'] - self.docs = coder['docs'] || '' - self.encoding = coder['encoding'] - self.extensions = coder['extensions'] || [] - self.preferred_extension = coder['preferred-extension'] - self.obsolete = coder['obsolete'] || false - self.registered = coder['registered'] || false - self.signature = coder['signature'] - self.xrefs = coder['xrefs'] || {} - self.use_instead = coder['use-instead'] + self.content_type = coder["content-type"] + self.docs = coder["docs"] || "" + self.encoding = coder["encoding"] + self.extensions = coder["extensions"] || [] + self.preferred_extension = coder["preferred-extension"] + self.obsolete = coder["obsolete"] || false + self.registered = coder["registered"] || false + self.signature = coder["signature"] + self.xrefs = coder["xrefs"] || {} + self.use_instead = coder["use-instead"] - friendly(coder['friendly'] || {}) + friendly(coder["friendly"] || {}) end def inspect # :nodoc: @@ -535,8 +537,8 @@ class MIME::Type # Converts a provided +content_type+ into a translation key suitable for # use with the I18n library. def i18n_key(content_type) - simplify_matchdata(match(content_type), joiner: '.') { |e| - e.gsub!(I18N_RE, '-') + simplify_matchdata(match(content_type), joiner: ".") { |e| + e.gsub!(I18N_RE, "-") } end @@ -553,12 +555,12 @@ class MIME::Type private - def simplify_matchdata(matchdata, remove_x = false, joiner: '/') + def simplify_matchdata(matchdata, remove_x = false, joiner: "/") return nil unless matchdata matchdata.captures.map { |e| e.downcase! - e.sub!(/^x-/, '') if remove_x + e.sub!(/^x-/, "") if remove_x yield e if block_given? e }.join(joiner) @@ -571,11 +573,11 @@ class MIME::Type match = MEDIA_TYPE_RE.match(type_string) fail InvalidContentType, type_string if match.nil? - @content_type = intern_string(type_string) + @content_type = intern_string(type_string) @raw_media_type, @raw_sub_type = match.captures - @simplified = intern_string(MIME::Type.simplified(match)) - @i18n_key = intern_string(MIME::Type.i18n_key(match)) - @media_type, @sub_type = MEDIA_TYPE_RE.match(@simplified).captures + @simplified = intern_string(MIME::Type.simplified(match)) + @i18n_key = intern_string(MIME::Type.i18n_key(match)) + @media_type, @sub_type = MEDIA_TYPE_RE.match(@simplified).captures @raw_media_type = intern_string(@raw_media_type) @raw_sub_type = intern_string(@raw_sub_type) @@ -600,22 +602,22 @@ class MIME::Type end def xref_url_for_rfc(value) - 'http://www.iana.org/go/%s' % value + "http://www.iana.org/go/%s" % value end def xref_url_for_draft(value) - 'http://www.iana.org/go/%s' % value.sub(/\ARFC/, 'draft') + "http://www.iana.org/go/%s" % value.sub(/\ARFC/, "draft") end def xref_url_for_rfc_errata(value) - 'http://www.rfc-editor.org/errata_search.php?eid=%s' % value + "http://www.rfc-editor.org/errata_search.php?eid=%s" % value end def xref_url_for_person(value) - 'http://www.iana.org/assignments/media-types/media-types.xhtml#%s' % value + "http://www.iana.org/assignments/media-types/media-types.xhtml#%s" % value end def xref_url_for_template(value) - 'http://www.iana.org/assignments/media-types/%s' % value + "http://www.iana.org/assignments/media-types/%s" % value end end diff --git a/lib/mime/type/columnar.rb b/lib/mime/type/columnar.rb index c29690e..93a3350 100644 --- a/lib/mime/type/columnar.rb +++ b/lib/mime/type/columnar.rb @@ -1,6 +1,6 @@ # frozen_string_literal: true -require 'mime/type' +require "mime/type" # A version of MIME::Type that works hand-in-hand with a MIME::Types::Columnar # container to load data by columns. @@ -36,7 +36,7 @@ class MIME::Type::Columnar < MIME::Type column :docs, :docs= column :preferred_extension, :preferred_extension= column :obsolete, :obsolete=, :obsolete?, :registered, :registered=, - :registered?, :signature, :signature=, :signature?, file: 'flags' + :registered?, :signature, :signature=, :signature?, file: "flags" column :xrefs, :xrefs=, :xref_urls column :use_instead, :use_instead= diff --git a/lib/mime/types.rb b/lib/mime/types.rb index 26ff937..2cf7fc4 100644 --- a/lib/mime/types.rb +++ b/lib/mime/types.rb @@ -7,7 +7,7 @@ module MIME end end -require 'mime/type' +require "mime/type" # MIME::Types is a registry of MIME types. It is both a class (created with # MIME::Types.new) and a default registry (loaded automatically or through @@ -72,8 +72,8 @@ class MIME::Types # Creates a new MIME::Types registry. def initialize - @type_variants = Container.new - @extension_index = Container.new + @type_variants = Container.new + @extension_index = Container.new end # Returns the number of known type variants. @@ -122,14 +122,15 @@ class MIME::Types # 5. Obsolete definitions use-instead clauses are compared. # 6. Sort on name. def [](type_id, complete: false, registered: false) - matches = case type_id + matches = + case type_id when MIME::Type @type_variants[type_id.simplified] when Regexp match(type_id) else @type_variants[MIME::Type.simplified(type_id)] - end + end prune_matches(matches, complete, registered).sort { |a, b| a.priority_compare(b) @@ -155,7 +156,7 @@ class MIME::Types a.priority_compare(b) } end - alias of type_for + alias_method :of, :type_for # Add one or more MIME::Type objects to the set of known types. If the # type is already known, a warning will be displayed. @@ -163,7 +164,7 @@ class MIME::Types # The last parameter may be the value <tt>:silent</tt> or +true+ which # will suppress duplicate MIME type warnings. def add(*types) - quiet = ((types.last == :silent) or (types.last == true)) + quiet = ((types.last == :silent) || (types.last == true)) types.each do |mime_type| case mime_type @@ -184,9 +185,9 @@ class MIME::Types # already known, a warning will be displayed. The +quiet+ parameter may be a # truthy value to suppress that warning. def add_type(type, quiet = false) - if !quiet and @type_variants[type.simplified].include?(type) - MIME::Types.logger.warn <<-WARNING -Type #{type} is already registered as a variant of #{type.simplified}. + if !quiet && @type_variants[type.simplified].include?(type) + MIME::Types.logger.warn <<~WARNING + Type #{type} is already registered as a variant of #{type.simplified}. WARNING end @@ -223,9 +224,9 @@ Type #{type} is already registered as a variant of #{type.simplified}. end end -require 'mime/types/cache' -require 'mime/types/container' -require 'mime/types/loader' -require 'mime/types/logger' -require 'mime/types/_columnar' -require 'mime/types/registry' +require "mime/types/cache" +require "mime/types/container" +require "mime/types/loader" +require "mime/types/logger" +require "mime/types/_columnar" +require "mime/types/registry" diff --git a/lib/mime/types/_columnar.rb b/lib/mime/types/_columnar.rb index f68bf61..777c316 100644 --- a/lib/mime/types/_columnar.rb +++ b/lib/mime/types/_columnar.rb @@ -1,6 +1,6 @@ # frozen_string_literal: true -require 'mime/type/columnar' +require "mime/type/columnar" # MIME::Types::Columnar is used to extend a MIME::Types container to load data # by columns instead of from JSON or YAML. Column loads of MIME types loaded @@ -22,7 +22,7 @@ module MIME::Types::Columnar def load_base_data(path) #:nodoc: @__root__ = path - each_file_line('content_type', false) do |line| + each_file_line("content_type", false) do |line| line = line.split content_type = line.shift extensions = line @@ -45,11 +45,11 @@ module MIME::Types::Columnar i = -1 column = File.join(@__root__, "mime.#{name}.column") - IO.readlines(column, encoding: 'UTF-8').each do |line| + IO.readlines(column, encoding: "UTF-8").each do |line| line.chomp! if lookup - type = @__mime_data__[i += 1] or next + (type = @__mime_data__[i += 1]) || next yield type, line else yield line @@ -61,26 +61,26 @@ module MIME::Types::Columnar end def load_encoding - each_file_line('encoding') do |type, line| + each_file_line("encoding") do |type, line| pool ||= {} type.instance_variable_set(:@encoding, (pool[line] ||= line)) end end def load_docs - each_file_line('docs') do |type, line| + each_file_line("docs") do |type, line| type.instance_variable_set(:@docs, opt(line)) end end def load_preferred_extension - each_file_line('pext') do |type, line| + each_file_line("pext") do |type, line| type.instance_variable_set(:@preferred_extension, opt(line)) end end def load_flags - each_file_line('flags') do |type, line| + each_file_line("flags") do |type, line| line = line.split type.instance_variable_set(:@obsolete, flag(line.shift)) type.instance_variable_set(:@registered, flag(line.shift)) @@ -89,29 +89,29 @@ module MIME::Types::Columnar end def load_xrefs - each_file_line('xrefs') { |type, line| + each_file_line("xrefs") { |type, line| type.instance_variable_set(:@xrefs, dict(line, array: true)) } end def load_friendly - each_file_line('friendly') { |type, line| + each_file_line("friendly") { |type, line| type.instance_variable_set(:@friendly, dict(line)) } end def load_use_instead - each_file_line('use_instead') do |type, line| + each_file_line("use_instead") do |type, line| type.instance_variable_set(:@use_instead, opt(line)) end end def dict(line, array: false) - if line == '-' + if line == "-" {} else - line.split('|').each_with_object({}) { |l, h| - k, v = l.split('^') + line.split("|").each_with_object({}) { |l, h| + k, v = l.split("^") v = nil if v.empty? h[k] = array ? Array(v) : v } @@ -119,18 +119,18 @@ module MIME::Types::Columnar end def arr(line) - if line == '-' + if line == "-" [] else - line.split('|').flatten.compact.uniq + line.split("|").flatten.compact.uniq end end def opt(line) - line unless line == '-' + line unless line == "-" end def flag(line) - line == '1' + line == "1" end end diff --git a/lib/mime/types/cache.rb b/lib/mime/types/cache.rb index e3d69c8..31113a6 100644 --- a/lib/mime/types/cache.rb +++ b/lib/mime/types/cache.rb @@ -15,21 +15,21 @@ class << MIME::Types::Cache # file does not exist, if the file cannot be loaded, or if the data in # the cache version is different than this version. def load(cache_file = nil) - cache_file ||= ENV['RUBY_MIME_TYPES_CACHE'] - return nil unless cache_file and File.exist?(cache_file) + cache_file ||= ENV["RUBY_MIME_TYPES_CACHE"] + return nil unless cache_file && File.exist?(cache_file) cache = Marshal.load(File.binread(cache_file)) if cache.version == MIME::Types::Data::VERSION Marshal.load(cache.data) else - MIME::Types.logger.warn <<-WARNING.chomp -Could not load MIME::Types cache: invalid version + MIME::Types.logger.warn <<~WARNING.chomp + Could not load MIME::Types cache: invalid version WARNING nil end rescue => e - MIME::Types.logger.warn <<-WARNING.chomp -Could not load MIME::Types cache: #{e} + MIME::Types.logger.warn <<~WARNING.chomp + Could not load MIME::Types cache: #{e} WARNING nil end @@ -44,12 +44,12 @@ Could not load MIME::Types cache: #{e} # +RUBY_MIME_TYPES_CACHE+. If there is no cache file specified either # directly or through the environment, this method will return +nil+ def save(types = nil, cache_file = nil) - cache_file ||= ENV['RUBY_MIME_TYPES_CACHE'] + cache_file ||= ENV["RUBY_MIME_TYPES_CACHE"] return nil unless cache_file types ||= MIME::Types.send(:__types__) - File.open(cache_file, 'wb') do |f| + File.open(cache_file, "wb") do |f| f.write( Marshal.dump(new(MIME::Types::Data::VERSION, Marshal.dump(types))) ) diff --git a/lib/mime/types/columnar.rb b/lib/mime/types/columnar.rb index 5c7dd73..dcb87cf 100644 --- a/lib/mime/types/columnar.rb +++ b/lib/mime/types/columnar.rb @@ -1,3 +1,3 @@ # frozen_string_literal: true -require 'mime/types' +require "mime/types" diff --git a/lib/mime/types/container.rb b/lib/mime/types/container.rb index 0f08622..094682b 100644 --- a/lib/mime/types/container.rb +++ b/lib/mime/types/container.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true -require 'set' -require 'forwardable' +require "set" +require "forwardable" # MIME::Types requires a serializable keyed container that returns an empty Set # on a key miss. Hash#default_value cannot be used because, while it traverses @@ -37,7 +37,7 @@ class MIME::Types::Container #:nodoc: def merge!(other) tap { - other = other.kind_of?(MIME::Types::Container) ? other.container : other + other = other.is_a?(MIME::Types::Container) ? other.container : other container.merge!(other) normalize } @@ -48,15 +48,15 @@ class MIME::Types::Container #:nodoc: end def_delegators :@container, - :==, - :count, - :each, - :each_value, - :empty?, - :flat_map, - :keys, - :select, - :values + :==, + :count, + :each, + :each_value, + :empty?, + :flat_map, + :keys, + :select, + :values def add(key, value) (container[key] ||= Set.new).add(value) @@ -85,7 +85,7 @@ class MIME::Types::Container #:nodoc: def normalize container.each do |k, v| - next if v.kind_of?(Set) + next if v.is_a?(Set) container[k] = Set[*v] end diff --git a/lib/mime/types/deprecations.rb b/lib/mime/types/deprecations.rb index 9de2946..8bd6455 100644 --- a/lib/mime/types/deprecations.rb +++ b/lib/mime/types/deprecations.rb @@ -1,6 +1,6 @@ # frozen_string_literal: true -require 'mime/types/logger' +require "mime/types/logger" # The namespace for MIME applications, tools, and libraries. module MIME @@ -8,25 +8,29 @@ module MIME class Types # Used to mark a method as deprecated in the mime-types interface. def self.deprecated(klass, sym, message = nil, &block) # :nodoc: - level = case klass + level = + case klass when Class, Module - '.' + "." else klass = klass.class - '#' - end - message = case message + "#" + end + message = + case message when :private, :protected "and will be #{message}" when nil - 'and will be removed' + "and will be removed" else message - end - MIME::Types.logger.warn <<-WARNING.chomp -#{caller[1]}: #{klass}#{level}#{sym} is deprecated #{message}. + end + MIME::Types.logger.warn <<~WARNING.chomp + #{caller(2..2).first}: #{klass}#{level}#{sym} is deprecated #{message}. WARNING - block.call if block + + return unless block + block.call end end end diff --git a/lib/mime/types/full.rb b/lib/mime/types/full.rb index 920ad2a..a69e6bd 100644 --- a/lib/mime/types/full.rb +++ b/lib/mime/types/full.rb @@ -9,11 +9,11 @@ module MIME private def load_mode - { columnar: false } + {columnar: false} end end end end end -require 'mime/types' +require "mime/types" diff --git a/lib/mime/types/loader.rb b/lib/mime/types/loader.rb index a38ba48..74fa63f 100644 --- a/lib/mime/types/loader.rb +++ b/lib/mime/types/loader.rb @@ -4,10 +4,11 @@ ## module MIME; end + ## class MIME::Types; end -require 'mime/types/data' +require "mime/types/data" # This class is responsible for initializing the MIME::Types registry from # the data files supplied with the mime-types library. @@ -30,7 +31,7 @@ class MIME::Types::Loader # Creates a Loader object that can be used to load MIME::Types registries # into memory, using YAML, JSON, or Columnar registry format loaders. def initialize(path = nil, container = nil) - path = path || ENV['RUBY_MIME_TYPES_DATA'] || MIME::Types::Data::PATH + path = path || ENV["RUBY_MIME_TYPES_DATA"] || MIME::Types::Data::PATH @container = container || MIME::Types.new @path = File.expand_path(path) end @@ -68,7 +69,7 @@ class MIME::Types::Loader # Loads a MIME::Types registry from columnar files recursively found in # +path+. def load_columnar - require 'mime/types/columnar' unless defined?(MIME::Types::Columnar) + require "mime/types/columnar" unless defined?(MIME::Types::Columnar) container.extend(MIME::Types::Columnar) container.load_base_data(path) @@ -80,7 +81,7 @@ class MIME::Types::Loader # # This will load from columnar files (#load_columnar) if <tt>columnar: # true</tt> is provided in +options+ and there are columnar files in +path+. - def load(options = { columnar: false }) + def load(options = {columnar: false}) if options[:columnar] && !Dir[columnar_path].empty? load_columnar else @@ -90,7 +91,7 @@ class MIME::Types::Loader class << self # Loads the default MIME::Type registry. - def load(options = { columnar: false }) + def load(options = {columnar: false}) new.load(options) end @@ -105,12 +106,18 @@ class MIME::Types::Loader # NOTE: The purpose of this format is purely for maintenance reasons. def load_from_yaml(filename) begin - require 'psych' + require "psych" rescue LoadError nil end - require 'yaml' - YAML.load(read_file(filename)) + + require "yaml" + + if old_yaml? + YAML.safe_load(read_file(filename), [MIME::Type]) + else + YAML.safe_load(read_file(filename), permitted_classes: [MIME::Type]) + end end # Loads MIME::Types from a single JSON file. @@ -119,28 +126,36 @@ class MIME::Types::Loader # The JSON format is the registry format for the MIME types registry # shipped with the mime-types library. def load_from_json(filename) - require 'json' + require "json" JSON.parse(read_file(filename)).map { |type| MIME::Type.new(type) } end private def read_file(filename) - File.open(filename, 'r:UTF-8:-', &:read) + File.open(filename, "r:UTF-8:-", &:read) + end + + def old_yaml? + @old_yaml ||= + begin + require "rubygems/version" + Gem::Version.new(YAML::VERSION) < Gem::Version.new("3.1") + end end end private def yaml_path - File.join(path, '*.y{,a}ml') + File.join(path, "*.y{,a}ml") end def json_path - File.join(path, '*.json') + File.join(path, "*.json") end def columnar_path - File.join(path, '*.column') + File.join(path, "*.column") end end diff --git a/lib/mime/types/logger.rb b/lib/mime/types/logger.rb index 927a4e5..a065fc3 100644 --- a/lib/mime/types/logger.rb +++ b/lib/mime/types/logger.rb @@ -2,7 +2,7 @@ # -*- ruby encoding: utf-8 -*- -require 'logger' +require "logger" ## module MIME diff --git a/lib/mime/types/registry.rb b/lib/mime/types/registry.rb index 5c8e5c7..8d92d65 100644 --- a/lib/mime/types/registry.rb +++ b/lib/mime/types/registry.rb @@ -33,7 +33,7 @@ class << MIME::Types def type_for(filename) __types__.type_for(filename) end - alias of type_for + alias_method :of, :type_for # MIME::Types#add against the default MIME::Types registry. def add(*types) @@ -43,22 +43,22 @@ class << MIME::Types private def lazy_load? - return unless ENV.key?('RUBY_MIME_TYPES_LAZY_LOAD') + return unless ENV.key?("RUBY_MIME_TYPES_LAZY_LOAD") - MIME::Types.logger.warn <<-WARNING.chomp -Lazy loading ($RUBY_MIME_TYPES_LAZY_LOAD) is deprecated and will be removed. + MIME::Types.logger.warn <<~WARNING.chomp + Lazy loading ($RUBY_MIME_TYPES_LAZY_LOAD) is deprecated and will be removed. WARNING - (lazy = ENV['RUBY_MIME_TYPES_LAZY_LOAD']) && (lazy != 'false') + (lazy = ENV["RUBY_MIME_TYPES_LAZY_LOAD"]) && (lazy != "false") end def __types__ - (defined?(@__types__) and @__types__) or load_default_mime_types + (defined?(@__types__) && @__types__) || load_default_mime_types end unless private_method_defined?(:load_mode) def load_mode - { columnar: true } + {columnar: true} end end diff --git a/mime-types.gemspec b/mime-types.gemspec index 3a2a61f..adf51e9 100644 --- a/mime-types.gemspec +++ b/mime-types.gemspec @@ -9,7 +9,7 @@ Gem::Specification.new do |s| s.metadata = { "bug_tracker_uri" => "https://github.com/mime-types/ruby-mime-types/issues", "changelog_uri" => "https://github.com/mime-types/ruby-mime-types/blob/master/History.md", "homepage_uri" => "https://github.com/mime-types/ruby-mime-types/", "source_code_uri" => "https://github.com/mime-types/ruby-mime-types/" } if s.respond_to? :metadata= s.require_paths = ["lib".freeze] s.authors = ["Austin Ziegler".freeze] - s.date = "2020-11-21" + s.date = "2021-06-02" s.description = "The mime-types library provides a library and registry for information about\nMIME content type definitions. It can be used to determine defined filename\nextensions for MIME types, or to use filename extensions to look up the likely\nMIME type definitions.\n\nVersion 3.0 is a major release that requires Ruby 2.0 compatibility and removes\ndeprecated functions. The columnar registry format introduced in 2.6 has been\nmade the primary format; the registry data has been extracted from this library\nand put into {mime-types-data}[https://github.com/mime-types/mime-types-data].\nAdditionally, mime-types is now licensed exclusively under the MIT licence and\nthere is a code of conduct in effect. There are a number of other smaller\nchanges described in the History file.".freeze s.email = ["halostatue@gmail.com".freeze] s.extra_rdoc_files = ["Code-of-Conduct.md".freeze, "Contributing.md".freeze, "History.md".freeze, "Licence.md".freeze, "Manifest.txt".freeze, "README.rdoc".freeze] @@ -18,57 +18,46 @@ Gem::Specification.new do |s| s.licenses = ["MIT".freeze] s.rdoc_options = ["--main".freeze, "README.rdoc".freeze] s.required_ruby_version = Gem::Requirement.new(">= 2.0".freeze) - s.rubygems_version = "3.0.3".freeze + s.rubygems_version = "3.1.6".freeze s.summary = "The mime-types library provides a library and registry for information about MIME content type definitions".freeze if s.respond_to? :specification_version then s.specification_version = 4 + end - if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then - s.add_runtime_dependency(%q<mime-types-data>.freeze, ["~> 3.2015"]) - s.add_development_dependency(%q<minitest>.freeze, ["~> 5.13"]) - s.add_development_dependency(%q<hoe-doofus>.freeze, ["~> 1.0"]) - s.add_development_dependency(%q<hoe-gemspec2>.freeze, ["~> 1.1"]) - s.add_development_dependency(%q<hoe-git>.freeze, ["~> 1.6"]) - s.add_development_dependency(%q<hoe-rubygems>.freeze, ["~> 1.0"]) - s.add_development_dependency(%q<minitest-autotest>.freeze, ["~> 1.0"]) - s.add_development_dependency(%q<minitest-focus>.freeze, ["~> 1.0"]) - s.add_development_dependency(%q<minitest-bonus-assertions>.freeze, ["~> 3.0"]) - s.add_development_dependency(%q<minitest-hooks>.freeze, ["~> 1.4"]) - s.add_development_dependency(%q<rake>.freeze, [">= 10.0", "< 14.0"]) - s.add_development_dependency(%q<simplecov>.freeze, ["~> 0.7"]) - s.add_development_dependency(%q<rdoc>.freeze, [">= 4.0", "< 7"]) - s.add_development_dependency(%q<hoe>.freeze, ["~> 3.20"]) - else - s.add_dependency(%q<mime-types-data>.freeze, ["~> 3.2015"]) - s.add_dependency(%q<minitest>.freeze, ["~> 5.13"]) - s.add_dependency(%q<hoe-doofus>.freeze, ["~> 1.0"]) - s.add_dependency(%q<hoe-gemspec2>.freeze, ["~> 1.1"]) - s.add_dependency(%q<hoe-git>.freeze, ["~> 1.6"]) - s.add_dependency(%q<hoe-rubygems>.freeze, ["~> 1.0"]) - s.add_dependency(%q<minitest-autotest>.freeze, ["~> 1.0"]) - s.add_dependency(%q<minitest-focus>.freeze, ["~> 1.0"]) - s.add_dependency(%q<minitest-bonus-assertions>.freeze, ["~> 3.0"]) - s.add_dependency(%q<minitest-hooks>.freeze, ["~> 1.4"]) - s.add_dependency(%q<rake>.freeze, [">= 10.0", "< 14.0"]) - s.add_dependency(%q<simplecov>.freeze, ["~> 0.7"]) - s.add_dependency(%q<rdoc>.freeze, [">= 4.0", "< 7"]) - s.add_dependency(%q<hoe>.freeze, ["~> 3.20"]) - end + if s.respond_to? :add_runtime_dependency then + s.add_runtime_dependency(%q<mime-types-data>.freeze, ["~> 3.2015"]) + s.add_development_dependency(%q<minitest>.freeze, ["~> 5.14"]) + s.add_development_dependency(%q<hoe-doofus>.freeze, ["~> 1.0"]) + s.add_development_dependency(%q<hoe-gemspec2>.freeze, ["~> 1.1"]) + s.add_development_dependency(%q<hoe-git>.freeze, ["~> 1.6"]) + s.add_development_dependency(%q<hoe-rubygems>.freeze, ["~> 1.0"]) + s.add_development_dependency(%q<standard>.freeze, ["~> 1.0"]) + s.add_development_dependency(%q<minitest-autotest>.freeze, ["~> 1.0"]) + s.add_development_dependency(%q<minitest-focus>.freeze, ["~> 1.0"]) + s.add_development_dependency(%q<minitest-bonus-assertions>.freeze, ["~> 3.0"]) + s.add_development_dependency(%q<minitest-hooks>.freeze, ["~> 1.4"]) + s.add_development_dependency(%q<rake>.freeze, [">= 10.0", "< 14.0"]) + s.add_development_dependency(%q<psych>.freeze, ["~> 3.0"]) + s.add_development_dependency(%q<simplecov>.freeze, ["~> 0.7"]) + s.add_development_dependency(%q<rdoc>.freeze, [">= 4.0", "< 7"]) + s.add_development_dependency(%q<hoe>.freeze, ["~> 3.23"]) else s.add_dependency(%q<mime-types-data>.freeze, ["~> 3.2015"]) - s.add_dependency(%q<minitest>.freeze, ["~> 5.13"]) + s.add_dependency(%q<minitest>.freeze, ["~> 5.14"]) s.add_dependency(%q<hoe-doofus>.freeze, ["~> 1.0"]) s.add_dependency(%q<hoe-gemspec2>.freeze, ["~> 1.1"]) s.add_dependency(%q<hoe-git>.freeze, ["~> 1.6"]) s.add_dependency(%q<hoe-rubygems>.freeze, ["~> 1.0"]) + s.add_dependency(%q<standard>.freeze, ["~> 1.0"]) s.add_dependency(%q<minitest-autotest>.freeze, ["~> 1.0"]) s.add_dependency(%q<minitest-focus>.freeze, ["~> 1.0"]) s.add_dependency(%q<minitest-bonus-assertions>.freeze, ["~> 3.0"]) s.add_dependency(%q<minitest-hooks>.freeze, ["~> 1.4"]) s.add_dependency(%q<rake>.freeze, [">= 10.0", "< 14.0"]) + s.add_dependency(%q<psych>.freeze, ["~> 3.0"]) s.add_dependency(%q<simplecov>.freeze, ["~> 0.7"]) s.add_dependency(%q<rdoc>.freeze, [">= 4.0", "< 7"]) - s.add_dependency(%q<hoe>.freeze, ["~> 3.20"]) + s.add_dependency(%q<hoe>.freeze, ["~> 3.23"]) end end diff --git a/support/benchmarks/load.rb b/support/benchmarks/load.rb index 0712676..a62359c 100644 --- a/support/benchmarks/load.rb +++ b/support/benchmarks/load.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true -require 'benchmark' -require 'mime/types' +require "benchmark" +require "mime/types" module Benchmarks # Benchmark loading speed @@ -11,10 +11,10 @@ module Benchmarks end def initialize(load_path, repeats = nil) - @cache_file = File.expand_path('../cache.mtc', __FILE__) - @repeats = repeats.to_i - @repeats = 50 if @repeats <= 0 - @load_path = load_path + @cache_file = File.expand_path("../cache.mtc", __FILE__) + @repeats = repeats.to_i + @repeats = 50 if @repeats <= 0 + @load_path = load_path end def reload_mime_types(repeats = 1, force: false, columnar: false, cache: false) @@ -34,26 +34,18 @@ module Benchmarks remove_cache Benchmark.bm(30) do |mark| - mark.report('Normal') do reload_mime_types(@repeats) end - mark.report('Columnar') do - reload_mime_types(@repeats, columnar: true) - end - mark.report('Columnar Full') do - reload_mime_types(@repeats, columnar: true, force: true) - end + mark.report("Normal") { reload_mime_types(@repeats) } + mark.report("Columnar") { reload_mime_types(@repeats, columnar: true) } + mark.report("Columnar Full") { reload_mime_types(@repeats, columnar: true, force: true) } - ENV['RUBY_MIME_TYPES_CACHE'] = @cache_file - mark.report('Cache Initialize') do reload_mime_types(cache: true) end - mark.report('Cached') do reload_mime_types(@repeats, cache: true) end + ENV["RUBY_MIME_TYPES_CACHE"] = @cache_file + mark.report("Cache Initialize") { reload_mime_types(cache: true) } + mark.report("Cached") { reload_mime_types(@repeats, cache: true) } remove_cache - ENV['RUBY_MIME_TYPES_CACHE'] = @cache_file - mark.report('Columnar Cache Initialize') do - reload_mime_types(columnar: true, cache: true) - end - mark.report('Columnar Cached') { - reload_mime_types(@repeats, columnar: true, cache: true) - } + ENV["RUBY_MIME_TYPES_CACHE"] = @cache_file + mark.report("Columnar Cache Initialize") { reload_mime_types(columnar: true, cache: true) } + mark.report("Columnar Cached") { reload_mime_types(@repeats, columnar: true, cache: true) } end ensure remove_cache diff --git a/support/benchmarks/load_allocations.rb b/support/benchmarks/load_allocations.rb index f97aa70..e05f71a 100644 --- a/support/benchmarks/load_allocations.rb +++ b/support/benchmarks/load_allocations.rb @@ -1,12 +1,12 @@ # frozen_string_literal: true -if RUBY_VERSION < '2.1' +if RUBY_VERSION < "2.1" warn "Cannot count allocations on #{RUBY_VERSION}." exit 1 end begin - require 'allocation_tracer' + require "allocation_tracer" rescue LoadError warn "Allocation tracking requires the gem 'allocation_tracer'." exit 1 @@ -48,13 +48,13 @@ module Benchmarks def report_top_x table = @allocations.sort_by { |_, v| v.first }.reverse.first(@top_x) table.map! { |(location, allocs)| - next if @mime_types_only and location.first !~ %r{mime-types/lib} + next if @mime_types_only && location.first !~ (%r{mime-types/lib}) - [location.join(':').gsub(%r{^#{Dir.pwd}/}, ''), *allocs] + [location.join(":").gsub(%r{^#{Dir.pwd}/}, ""), *allocs] }.compact! head = (ObjectSpace::AllocationTracer.header - [:line]).map { |h| - h.to_s.split(/_/).map(&:capitalize).join(' ') + h.to_s.split("_").map(&:capitalize).join(" ") } table.unshift head @@ -66,8 +66,8 @@ module Benchmarks end } - pattern = ['%%-%ds'] - pattern << (['%% %ds'] * (max_widths.length - 1)) + pattern = ["%%-%ds"] + pattern << (["%% %ds"] * (max_widths.length - 1)) pattern = pattern.join("\t") % max_widths table.each do |row| puts pattern % row @@ -79,17 +79,17 @@ module Benchmarks @allocations = if @columnar ObjectSpace::AllocationTracer.trace do - require 'mime/types' + require "mime/types" MIME::Types.first.to_h if @full end else ObjectSpace::AllocationTracer.trace do - require 'mime/types/full' + require "mime/types/full" end end - @count = ObjectSpace::AllocationTracer.allocated_count_table.values. - inject(:+) + @count = ObjectSpace::AllocationTracer.allocated_count_table.values + .inject(:+) end end end diff --git a/support/benchmarks/memory_profiler.rb b/support/benchmarks/memory_profiler.rb index c5ae405..f3bc20e 100644 --- a/support/benchmarks/memory_profiler.rb +++ b/support/benchmarks/memory_profiler.rb @@ -1,12 +1,12 @@ # frozen_string_literal: true -if RUBY_VERSION < '2.3' - warn 'Cannot use memory_profiler on less than 2.3.8.' +if RUBY_VERSION < "2.3" + warn "Cannot use memory_profiler on less than 2.3.8." exit 1 end begin - require 'memory_profiler' + require "memory_profiler" rescue Exception # rubocop:disable Lint/RescueException warn "Memory profiling requires the gem 'memory_profiler'." exit 1 @@ -51,12 +51,12 @@ module Benchmarks if @columnar MemoryProfiler.report(**report_params) do - require 'mime/types' + require "mime/types" MIME::Types.first.to_h if @full end else MemoryProfiler.report(**report_params) do - require 'mime/types/full' + require "mime/types/full" end end end diff --git a/support/benchmarks/object_counts.rb b/support/benchmarks/object_counts.rb index d548bd1..b906077 100644 --- a/support/benchmarks/object_counts.rb +++ b/support/benchmarks/object_counts.rb @@ -17,7 +17,7 @@ module Benchmarks @before.keys.grep(/T_/).map { |key| [key, @after[key] - @before[key]] }.sort_by { |_, delta| -delta }.each { |key, delta| - puts '%10s +%6d' % [key, delta] + puts "%10s +%6d" % [key, delta] } end @@ -27,10 +27,10 @@ module Benchmarks @before = count_objects if @columnar - require 'mime/types' + require "mime/types" MIME::Types.first.to_h if @full else - require 'mime/types/full' + require "mime/types/full" end @after = count_objects diff --git a/test/minitest_helper.rb b/test/minitest_helper.rb index f91ed8e..44973e3 100644 --- a/test/minitest_helper.rb +++ b/test/minitest_helper.rb @@ -1,11 +1,11 @@ # frozen_string_literal: true -require 'mime/type' -require 'fileutils' +require "mime/type" +require "fileutils" -gem 'minitest' -require 'minitest/focus' -require 'minitest-bonus-assertions' -require 'minitest/hooks' +gem "minitest" +require "minitest/focus" +require "minitest-bonus-assertions" +require "minitest/hooks" -ENV['RUBY_MIME_TYPES_LAZY_LOAD'] = 'yes' +ENV["RUBY_MIME_TYPES_LAZY_LOAD"] = "yes" diff --git a/test/test_mime_type.rb b/test/test_mime_type.rb index 891c04e..87cbfb8 100644 --- a/test/test_mime_type.rb +++ b/test/test_mime_type.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true -require 'mime/types' -require 'minitest_helper' +require "mime/types" +require "minitest_helper" describe MIME::Type do def mime_type(content_type) @@ -9,299 +9,299 @@ describe MIME::Type do end let(:x_appl_x_zip) { - mime_type('x-appl/x-zip') { |t| t.extensions = %w(zip zp) } + mime_type("x-appl/x-zip") { |t| t.extensions = %w[zip zp] } } - let(:text_plain) { mime_type('text/plain') } - let(:text_html) { mime_type('text/html') } - let(:image_jpeg) { mime_type('image/jpeg') } + let(:text_plain) { mime_type("text/plain") } + let(:text_html) { mime_type("text/html") } + let(:image_jpeg) { mime_type("image/jpeg") } let(:application_javascript) { - mime_type('application/javascript') do |js| - js.friendly('en' => 'JavaScript') + mime_type("application/javascript") do |js| + js.friendly("en" => "JavaScript") js.xrefs = { - 'rfc' => %w(rfc4239 rfc4239), - 'template' => %w(application/javascript) + "rfc" => %w[rfc4239 rfc4239], + "template" => %w[application/javascript] } - js.encoding = '8bit' - js.extensions = %w(js sj) + js.encoding = "8bit" + js.extensions = %w[js sj] js.registered = true end } let(:text_x_yaml) { - mime_type('text/x-yaml') do |yaml| - yaml.extensions = %w(yaml yml) - yaml.encoding = '8bit' - yaml.friendly('en' => 'YAML Structured Document') + mime_type("text/x-yaml") do |yaml| + yaml.extensions = %w[yaml yml] + yaml.encoding = "8bit" + yaml.friendly("en" => "YAML Structured Document") end } let(:text_x_yaml_with_docs) { text_x_yaml.dup.tap do |yaml| - yaml.docs = 'Test YAML' + yaml.docs = "Test YAML" end } - describe '.simplified' do - it 'leaves normal types alone' do - assert_equal 'text/plain', MIME::Type.simplified('text/plain') + describe ".simplified" do + it "leaves normal types alone" do + assert_equal "text/plain", MIME::Type.simplified("text/plain") end - it 'does not remove x- prefixes by default' do - assert_equal 'application/x-msword', - MIME::Type.simplified('application/x-msword') - assert_equal 'x-xyz/abc', MIME::Type.simplified('x-xyz/abc') + it "does not remove x- prefixes by default" do + assert_equal "application/x-msword", + MIME::Type.simplified("application/x-msword") + assert_equal "x-xyz/abc", MIME::Type.simplified("x-xyz/abc") end - it 'removes x- prefixes when requested' do - assert_equal 'application/msword', - MIME::Type.simplified('application/x-msword', remove_x_prefix: true) - assert_equal 'xyz/abc', - MIME::Type.simplified('x-xyz/abc', remove_x_prefix: true) + it "removes x- prefixes when requested" do + assert_equal "application/msword", + MIME::Type.simplified("application/x-msword", remove_x_prefix: true) + assert_equal "xyz/abc", + MIME::Type.simplified("x-xyz/abc", remove_x_prefix: true) end - it 'lowercases mixed-case types' do - assert_equal 'text/vcard', MIME::Type.simplified('text/vCard') + it "lowercases mixed-case types" do + assert_equal "text/vcard", MIME::Type.simplified("text/vCard") end - it 'returns nil when the value provided is not a valid content type' do - assert_nil MIME::Type.simplified('text') + it "returns nil when the value provided is not a valid content type" do + assert_nil MIME::Type.simplified("text") end end - describe '.i18n_key' do - it 'converts text/plain to text.plain' do - assert_equal 'text.plain', MIME::Type.i18n_key('text/plain') + describe ".i18n_key" do + it "converts text/plain to text.plain" do + assert_equal "text.plain", MIME::Type.i18n_key("text/plain") end - it 'does not remove x-prefixes' do - assert_equal 'application.x-msword', - MIME::Type.i18n_key('application/x-msword') + it "does not remove x-prefixes" do + assert_equal "application.x-msword", + MIME::Type.i18n_key("application/x-msword") end - it 'converts text/vCard to text.vcard' do - assert_equal 'text.vcard', MIME::Type.i18n_key('text/vCard') + it "converts text/vCard to text.vcard" do + assert_equal "text.vcard", MIME::Type.i18n_key("text/vCard") end - it 'returns nil when the value provided is not a valid content type' do - assert_nil MIME::Type.i18n_key('text') + it "returns nil when the value provided is not a valid content type" do + assert_nil MIME::Type.i18n_key("text") end end - describe '.new' do - it 'fails if an invalid content type is provided' do + describe ".new" do + it "fails if an invalid content type is provided" do exception = assert_raises MIME::Type::InvalidContentType do - MIME::Type.new('apps') + MIME::Type.new("apps") end assert_equal 'Invalid Content-Type "apps"', exception.to_s end - it 'creates a valid content type just from a string' do - type = MIME::Type.new('text/x-yaml') + it "creates a valid content type just from a string" do + type = MIME::Type.new("text/x-yaml") assert_instance_of MIME::Type, type - assert_equal 'text/x-yaml', type.content_type + assert_equal "text/x-yaml", type.content_type end - it 'yields the content type in a block' do - MIME::Type.new('text/x-yaml') do |type| + it "yields the content type in a block" do + MIME::Type.new("text/x-yaml") do |type| assert_instance_of MIME::Type, type - assert_equal 'text/x-yaml', type.content_type + assert_equal "text/x-yaml", type.content_type end end - it 'creates a valid content type from a hash' do + it "creates a valid content type from a hash" do type = MIME::Type.new( - 'content-type' => 'text/x-yaml', - 'obsolete' => true + "content-type" => "text/x-yaml", + "obsolete" => true ) assert_instance_of MIME::Type, type - assert_equal 'text/x-yaml', type.content_type + assert_equal "text/x-yaml", type.content_type assert type.obsolete? end - it 'creates a valid content type from an array' do - type = MIME::Type.new(%w(text/x-yaml yaml yml yz)) + it "creates a valid content type from an array" do + type = MIME::Type.new(%w[text/x-yaml yaml yml yz]) assert_instance_of MIME::Type, type - assert_equal 'text/x-yaml', type.content_type - assert_equal %w(yaml yml yz), type.extensions + assert_equal "text/x-yaml", type.content_type + assert_equal %w[yaml yml yz], type.extensions end end - describe '#like?' do - it 'compares two MIME::Types on #simplified values without x- prefixes' do + describe "#like?" do + it "compares two MIME::Types on #simplified values without x- prefixes" do assert text_plain.like?(text_plain) refute text_plain.like?(text_html) end - it 'compares MIME::Type against string without x- prefixes' do + it "compares MIME::Type against string without x- prefixes" do assert text_plain.like?(text_plain.to_s) refute text_plain.like?(text_html.to_s) end end - describe '#<=>' do - it 'correctly compares identical types' do + describe "#<=>" do + it "correctly compares identical types" do assert_equal text_plain, text_plain end - it 'correctly compares equivalent types' do - right = mime_type('text/Plain') + it "correctly compares equivalent types" do + right = mime_type("text/Plain") refute_same text_plain, right assert_equal text_plain, right end - it 'correctly compares types that sort earlier' do + it "correctly compares types that sort earlier" do refute_equal text_html, text_plain assert_operator text_html, :<, text_plain end - it 'correctly compares types that sort later' do + it "correctly compares types that sort later" do refute_equal text_plain, text_html assert_operator text_plain, :>, text_html end - it 'correctly compares types against equivalent strings' do - assert_equal text_plain, 'text/plain' + it "correctly compares types against equivalent strings" do + assert_equal text_plain, "text/plain" end - it 'correctly compares types against strings that sort earlier' do - refute_equal text_html, 'text/plain' - assert_operator text_html, :<, 'text/plain' + it "correctly compares types against strings that sort earlier" do + refute_equal text_html, "text/plain" + assert_operator text_html, :<, "text/plain" end - it 'correctly compares types against strings that sort later' do - refute_equal text_plain, 'text/html' - assert_operator text_plain, :>, 'text/html' + it "correctly compares types against strings that sort later" do + refute_equal text_plain, "text/html" + assert_operator text_plain, :>, "text/html" end - it 'correctly compares against nil' do + it "correctly compares against nil" do refute_equal text_html, nil assert_operator text_plain, :<, nil end end - describe '#ascii?' do - it 'defaults to true for text/* types' do + describe "#ascii?" do + it "defaults to true for text/* types" do assert text_plain.ascii? end - it 'defaults to false for non-text/* types' do + it "defaults to false for non-text/* types" do refute image_jpeg.ascii? end end - describe '#binary?' do - it 'defaults to false for text/* types' do + describe "#binary?" do + it "defaults to false for text/* types" do refute text_plain.binary? end - it 'defaults to true for non-text/* types' do + it "defaults to true for non-text/* types" do assert image_jpeg.binary? end end - describe '#complete?' do - it 'is true when there are extensions' do + describe "#complete?" do + it "is true when there are extensions" do assert text_x_yaml.complete? end - it 'is false when there are no extensions' do - refute mime_type('text/plain').complete? + it "is false when there are no extensions" do + refute mime_type("text/plain").complete? end end - describe '#content_type' do - it 'preserves the original case' do - assert_equal 'text/plain', text_plain.content_type - assert_equal 'text/vCard', mime_type('text/vCard').content_type + describe "#content_type" do + it "preserves the original case" do + assert_equal "text/plain", text_plain.content_type + assert_equal "text/vCard", mime_type("text/vCard").content_type end - it 'does not remove x- prefixes' do - assert_equal 'x-appl/x-zip', x_appl_x_zip.content_type + it "does not remove x- prefixes" do + assert_equal "x-appl/x-zip", x_appl_x_zip.content_type end end - describe '#default_encoding' do - it 'is quoted-printable for text/* types' do - assert_equal 'quoted-printable', text_plain.default_encoding + describe "#default_encoding" do + it "is quoted-printable for text/* types" do + assert_equal "quoted-printable", text_plain.default_encoding end - it 'is base64 for non-text/* types' do - assert_equal 'base64', image_jpeg.default_encoding + it "is base64 for non-text/* types" do + assert_equal "base64", image_jpeg.default_encoding end end - describe '#encoding, #encoding=' do - it 'returns #default_encoding if not set explicitly' do - assert_equal 'quoted-printable', text_plain.encoding - assert_equal 'base64', image_jpeg.encoding + describe "#encoding, #encoding=" do + it "returns #default_encoding if not set explicitly" do + assert_equal "quoted-printable", text_plain.encoding + assert_equal "base64", image_jpeg.encoding end - it 'returns the set value when set' do - text_plain.encoding = '8bit' - assert_equal '8bit', text_plain.encoding + it "returns the set value when set" do + text_plain.encoding = "8bit" + assert_equal "8bit", text_plain.encoding end - it 'resets to the default encoding when set to nil or :default' do - text_plain.encoding = '8bit' + it "resets to the default encoding when set to nil or :default" do + text_plain.encoding = "8bit" text_plain.encoding = nil assert_equal text_plain.default_encoding, text_plain.encoding text_plain.encoding = :default assert_equal text_plain.default_encoding, text_plain.encoding end - it 'raises a MIME::Type::InvalidEncoding for an invalid encoding' do + it "raises a MIME::Type::InvalidEncoding for an invalid encoding" do exception = assert_raises MIME::Type::InvalidEncoding do - text_plain.encoding = 'binary' + text_plain.encoding = "binary" end assert_equal 'Invalid Encoding "binary"', exception.to_s end end - describe '#eql?' do - it 'is not true for a non-MIME::Type' do - refute text_plain.eql?('text/plain') + describe "#eql?" do + it "is not true for a non-MIME::Type" do + refute text_plain.eql?("text/plain") end - it 'is not true for a different MIME::Type' do + it "is not true for a different MIME::Type" do refute text_plain.eql?(image_jpeg) end - it 'is true for an equivalent MIME::Type' do - assert text_plain, mime_type('text/Plain') + it "is true for an equivalent MIME::Type" do + assert text_plain, mime_type("text/Plain") end end - describe '#extensions, #extensions=' do - it 'returns an array of extensions' do - assert_equal %w(yaml yml), text_x_yaml.extensions - assert_equal %w(zip zp), x_appl_x_zip.extensions + describe "#extensions, #extensions=" do + it "returns an array of extensions" do + assert_equal %w[yaml yml], text_x_yaml.extensions + assert_equal %w[zip zp], x_appl_x_zip.extensions end - it 'sets a single extension when provided a single value' do - text_x_yaml.extensions = 'yaml' - assert_equal %w(yaml), text_x_yaml.extensions + it "sets a single extension when provided a single value" do + text_x_yaml.extensions = "yaml" + assert_equal %w[yaml], text_x_yaml.extensions end - it 'deduplicates extensions' do - text_x_yaml.extensions = %w(yaml yaml) - assert_equal %w(yaml), text_x_yaml.extensions + it "deduplicates extensions" do + text_x_yaml.extensions = %w[yaml yaml] + assert_equal %w[yaml], text_x_yaml.extensions end end - describe '#add_extensions' do - it 'does not modify extensions when provided nil' do + describe "#add_extensions" do + it "does not modify extensions when provided nil" do text_x_yaml.add_extensions(nil) - assert_equal %w(yaml yml), text_x_yaml.extensions + assert_equal %w[yaml yml], text_x_yaml.extensions end - it 'remains deduplicated with duplicate values' do - text_x_yaml.add_extensions('yaml') - assert_equal %w(yaml yml), text_x_yaml.extensions - text_x_yaml.add_extensions(%w(yaml yz)) - assert_equal %w(yaml yml yz), text_x_yaml.extensions + it "remains deduplicated with duplicate values" do + text_x_yaml.add_extensions("yaml") + assert_equal %w[yaml yml], text_x_yaml.extensions + text_x_yaml.add_extensions(%w[yaml yz]) + assert_equal %w[yaml yml yz], text_x_yaml.extensions end end - describe '#priority_compare' do + describe "#priority_compare" do def assert_priority_less(left, right) assert_equal(-1, left.priority_compare(right)) end @@ -320,17 +320,17 @@ describe MIME::Type do assert_priority_more right, left end - let(:text_1) { mime_type('text/1') } - let(:text_1p) { mime_type('text/1') } - let(:text_2) { mime_type('text/2') } + let(:text_1) { mime_type("text/1") } + let(:text_1p) { mime_type("text/1") } + let(:text_2) { mime_type("text/2") } - it 'sorts (1) based on the simplified type' do + it "sorts (1) based on the simplified type" do assert_priority text_1, text_1p, text_2 end - it 'sorts (2) based on extensions' do - text_1.extensions = ['foo', 'bar'] - text_2.extensions = ['foo'] + it "sorts (2) based on extensions" do + text_1.extensions = ["foo", "bar"] + text_2.extensions = ["foo"] assert_priority_same text_1, text_2 @@ -339,272 +339,272 @@ describe MIME::Type do assert_priority_more text_1, text_2 end - it 'sorts (3) based on the registration state' do + it "sorts (3) based on the registration state" do text_1.registered = text_1p.registered = true text_1b = mime_type(text_1) { |t| t.registered = false } assert_priority text_1, text_1p, text_1b end - it 'sorts (4) based on the completeness' do - text_1.extensions = text_1p.extensions = '1' + it "sorts (4) based on the completeness" do + text_1.extensions = text_1p.extensions = "1" text_1b = mime_type(text_1) { |t| t.extensions = nil } assert_priority text_1, text_1p, text_1b end - it 'sorts (5) based on obsolete status' do + it "sorts (5) based on obsolete status" do text_1.obsolete = text_1p.obsolete = false text_1b = mime_type(text_1) { |t| t.obsolete = true } assert_priority text_1, text_1p, text_1b end - it 'sorts (5) based on the use-instead value' do + it "sorts (5) based on the use-instead value" do text_1.obsolete = text_1p.obsolete = true - text_1.use_instead = text_1p.use_instead = 'abc/xyz' + text_1.use_instead = text_1p.use_instead = "abc/xyz" text_1b = mime_type(text_1) { |t| t.use_instead = nil } assert_priority text_1, text_1p, text_1b - text_1b.use_instead = 'abc/zzz' + text_1b.use_instead = "abc/zzz" assert_priority text_1, text_1p, text_1b end end - describe '#raw_media_type' do - it 'extracts the media type as case-preserved' do - assert_equal 'Text', mime_type('Text/plain').raw_media_type + describe "#raw_media_type" do + it "extracts the media type as case-preserved" do + assert_equal "Text", mime_type("Text/plain").raw_media_type end - it 'does not remove x- prefixes' do - assert_equal('x-appl', x_appl_x_zip.raw_media_type) + it "does not remove x- prefixes" do + assert_equal("x-appl", x_appl_x_zip.raw_media_type) end end - describe '#media_type' do - it 'extracts the media type as lowercase' do - assert_equal 'text', text_plain.media_type + describe "#media_type" do + it "extracts the media type as lowercase" do + assert_equal "text", text_plain.media_type end - it 'does not remove x- prefixes' do - assert_equal('x-appl', x_appl_x_zip.media_type) + it "does not remove x- prefixes" do + assert_equal("x-appl", x_appl_x_zip.media_type) end end - describe '#raw_media_type' do - it 'extracts the media type as case-preserved' do - assert_equal 'Text', mime_type('Text/plain').raw_media_type + describe "#raw_media_type" do + it "extracts the media type as case-preserved" do + assert_equal "Text", mime_type("Text/plain").raw_media_type end - it 'does not remove x- prefixes' do - assert_equal('x-appl', x_appl_x_zip.raw_media_type) + it "does not remove x- prefixes" do + assert_equal("x-appl", x_appl_x_zip.raw_media_type) end end - describe '#sub_type' do - it 'extracts the sub type as lowercase' do - assert_equal 'plain', text_plain.sub_type + describe "#sub_type" do + it "extracts the sub type as lowercase" do + assert_equal "plain", text_plain.sub_type end - it 'does not remove x- prefixes' do - assert_equal('x-zip', x_appl_x_zip.sub_type) + it "does not remove x- prefixes" do + assert_equal("x-zip", x_appl_x_zip.sub_type) end end - describe '#raw_sub_type' do - it 'extracts the sub type as case-preserved' do - assert_equal 'Plain', mime_type('text/Plain').raw_sub_type + describe "#raw_sub_type" do + it "extracts the sub type as case-preserved" do + assert_equal "Plain", mime_type("text/Plain").raw_sub_type end - it 'does not remove x- prefixes' do - assert_equal('x-zip', x_appl_x_zip.raw_sub_type) + it "does not remove x- prefixes" do + assert_equal("x-zip", x_appl_x_zip.raw_sub_type) end end - describe '#to_h' do - let(:t) { mime_type('a/b') } + describe "#to_h" do + let(:t) { mime_type("a/b") } - it 'has the required keys (content-type, registered, encoding)' do - assert_has_keys t.to_h, %w(content-type registered encoding) + it "has the required keys (content-type, registered, encoding)" do + assert_has_keys t.to_h, %w[content-type registered encoding] end - it 'has the docs key if there are documents' do - assert_has_keys mime_type(t) { |v| v.docs = 'a' }.to_h, %w(docs) + it "has the docs key if there are documents" do + assert_has_keys mime_type(t) { |v| v.docs = "a" }.to_h, %w[docs] end - it 'has the extensions key if set' do - assert_has_keys mime_type(t) { |v| v.extensions = 'a' }.to_h, - 'extensions' + it "has the extensions key if set" do + assert_has_keys mime_type(t) { |v| v.extensions = "a" }.to_h, + "extensions" end - it 'has the preferred-extension key if set' do - assert_has_keys mime_type(t) { |v| v.preferred_extension = 'a' }.to_h, - 'preferred-extension' + it "has the preferred-extension key if set" do + assert_has_keys mime_type(t) { |v| v.preferred_extension = "a" }.to_h, + "preferred-extension" end - it 'has the obsolete key if set' do - assert_has_keys mime_type(t) { |v| v.obsolete = true }.to_h, 'obsolete' + it "has the obsolete key if set" do + assert_has_keys mime_type(t) { |v| v.obsolete = true }.to_h, "obsolete" end - it 'has the obsolete and use-instead keys if set' do + it "has the obsolete and use-instead keys if set" do assert_has_keys mime_type(t) { |v| v.obsolete = true - v.use_instead = 'c/d' - }.to_h, %w(obsolete use-instead) + v.use_instead = "c/d" + }.to_h, %w[obsolete use-instead] end - it 'has the signature key if set' do - assert_has_keys mime_type(t) { |v| v.signature = true }.to_h, 'signature' + it "has the signature key if set" do + assert_has_keys mime_type(t) { |v| v.signature = true }.to_h, "signature" end end - describe '#to_json' do + describe "#to_json" do let(:expected) { '{"content-type":"a/b","encoding":"base64","registered":false}' } - it 'converts to JSON when requested' do - assert_equal expected, mime_type('a/b').to_json + it "converts to JSON when requested" do + assert_equal expected, mime_type("a/b").to_json end end - describe '#to_s, #to_str' do - it 'represents itself as a string of the canonical content_type' do - assert_equal 'text/plain', text_plain.to_s + describe "#to_s, #to_str" do + it "represents itself as a string of the canonical content_type" do + assert_equal "text/plain", text_plain.to_s end - it 'acts like a string of the canonical content_type for comparison' do - assert_equal text_plain, 'text/plain' + it "acts like a string of the canonical content_type for comparison" do + assert_equal text_plain, "text/plain" end - it 'acts like a string for other purposes' do - assert_equal 'stringy', 'text/plain'.sub(text_plain, 'stringy') + it "acts like a string for other purposes" do + assert_equal "stringy", "text/plain".sub(text_plain, "stringy") end end - describe '#xrefs, #xrefs=' do + describe "#xrefs, #xrefs=" do let(:expected) { - MIME::Types::Container.new('rfc' => Set['rfc1234', 'rfc5678']) + MIME::Types::Container.new("rfc" => Set["rfc1234", "rfc5678"]) } - it 'returns the expected results' do + it "returns the expected results" do application_javascript.xrefs = { - 'rfc' => %w(rfc5678 rfc1234 rfc1234) + "rfc" => %w[rfc5678 rfc1234 rfc1234] } assert_equal expected, application_javascript.xrefs end end - describe '#xref_urls' do + describe "#xref_urls" do let(:expected) { [ - 'http://www.iana.org/go/draft1', - 'http://www.iana.org/assignments/media-types/a/b', - 'http://www.iana.org/assignments/media-types/media-types.xhtml#p-1', - 'http://www.iana.org/go/rfc-1', - 'http://www.rfc-editor.org/errata_search.php?eid=err-1', - 'http://example.org', - 'text' + "http://www.iana.org/go/draft1", + "http://www.iana.org/assignments/media-types/a/b", + "http://www.iana.org/assignments/media-types/media-types.xhtml#p-1", + "http://www.iana.org/go/rfc-1", + "http://www.rfc-editor.org/errata_search.php?eid=err-1", + "http://example.org", + "text" ] } let(:type) { - mime_type('a/b').tap do |t| + mime_type("a/b").tap do |t| t.xrefs = { - 'draft' => ['RFC1'], - 'template' => ['a/b'], - 'person' => ['p-1'], - 'rfc' => ['rfc-1'], - 'rfc-errata' => ['err-1'], - 'uri' => ['http://example.org'], - 'text' => ['text'] + "draft" => ["RFC1"], + "template" => ["a/b"], + "person" => ["p-1"], + "rfc" => ["rfc-1"], + "rfc-errata" => ["err-1"], + "uri" => ["http://example.org"], + "text" => ["text"] } end } - it 'translates according to given rules' do + it "translates according to given rules" do assert_equal expected, type.xref_urls end end - describe '#use_instead' do - it 'is nil unless the type is obsolete' do + describe "#use_instead" do + it "is nil unless the type is obsolete" do assert_nil text_plain.use_instead end - it 'is nil if not set and the type is obsolete' do + it "is nil if not set and the type is obsolete" do text_plain.obsolete = true assert_nil text_plain.use_instead end - it 'is a different type if set and the type is obsolete' do + it "is a different type if set and the type is obsolete" do text_plain.obsolete = true - text_plain.use_instead = 'text/html' - assert_equal 'text/html', text_plain.use_instead + text_plain.use_instead = "text/html" + assert_equal "text/html", text_plain.use_instead end end - describe '#preferred_extension, #preferred_extension=' do - it 'is nil when not set and there are no extensions' do + describe "#preferred_extension, #preferred_extension=" do + it "is nil when not set and there are no extensions" do assert_nil text_plain.preferred_extension end - it 'is the first extension when not set but there are extensions' do - assert_equal 'yaml', text_x_yaml.preferred_extension + it "is the first extension when not set but there are extensions" do + assert_equal "yaml", text_x_yaml.preferred_extension end - it 'is the extension provided when set' do - text_x_yaml.preferred_extension = 'yml' - assert_equal 'yml', text_x_yaml.preferred_extension + it "is the extension provided when set" do + text_x_yaml.preferred_extension = "yml" + assert_equal "yml", text_x_yaml.preferred_extension end - it 'is adds the preferred extension if it does not exist' do - text_x_yaml.preferred_extension = 'yz' - assert_equal 'yz', text_x_yaml.preferred_extension - assert_includes text_x_yaml.extensions, 'yz' + it "is adds the preferred extension if it does not exist" do + text_x_yaml.preferred_extension = "yz" + assert_equal "yz", text_x_yaml.preferred_extension + assert_includes text_x_yaml.extensions, "yz" end end - describe '#friendly' do - it 'returns English by default' do - assert_equal 'YAML Structured Document', text_x_yaml.friendly + describe "#friendly" do + it "returns English by default" do + assert_equal "YAML Structured Document", text_x_yaml.friendly end - it 'returns English when requested' do - assert_equal 'YAML Structured Document', text_x_yaml.friendly('en') - assert_equal 'YAML Structured Document', text_x_yaml.friendly(:en) + it "returns English when requested" do + assert_equal "YAML Structured Document", text_x_yaml.friendly("en") + assert_equal "YAML Structured Document", text_x_yaml.friendly(:en) end - it 'returns nothing for an unknown language' do - assert_nil text_x_yaml.friendly('zz') + it "returns nothing for an unknown language" do + assert_nil text_x_yaml.friendly("zz") end - it 'merges new values from an array parameter' do - expected = { 'en' => 'Text files' } - assert_equal expected, text_plain.friendly(['en', 'Text files']) - expected.update('fr' => 'des fichiers texte') + it "merges new values from an array parameter" do + expected = {"en" => "Text files"} + assert_equal expected, text_plain.friendly(["en", "Text files"]) + expected.update("fr" => "des fichiers texte") assert_equal expected, - text_plain.friendly(['fr', 'des fichiers texte']) + text_plain.friendly(["fr", "des fichiers texte"]) end - it 'merges new values from a hash parameter' do - expected = { 'en' => 'Text files' } + it "merges new values from a hash parameter" do + expected = {"en" => "Text files"} assert_equal expected, text_plain.friendly(expected) - french = { 'fr' => 'des fichiers texte' } + french = {"fr" => "des fichiers texte"} expected.update(french) assert_equal expected, text_plain.friendly(french) end - it 'raises an ArgumentError if an unknown value is provided' do + it "raises an ArgumentError if an unknown value is provided" do exception = assert_raises ArgumentError do text_plain.friendly(1) end - assert_equal 'Expected a language or translation set, not 1', - exception.message + assert_equal "Expected a language or translation set, not 1", + exception.message end end end diff --git a/test/test_mime_types.rb b/test/test_mime_types.rb index 6a9689f..b01b702 100644 --- a/test/test_mime_types.rb +++ b/test/test_mime_types.rb @@ -1,128 +1,128 @@ # frozen_string_literal: true -require 'mime/types' -require 'minitest_helper' +require "mime/types" +require "minitest_helper" describe MIME::Types do def mime_types @mime_types ||= MIME::Types.new.tap { |mt| - mt.add MIME::Type.new(['text/plain', %w(txt)]), - MIME::Type.new(['image/jpeg', %w(jpg jpeg)]), - MIME::Type.new('application/x-wordperfect6.1'), - MIME::Type.new( - 'content-type' => 'application/x-www-form-urlencoded', - 'registered' => true - ), - MIME::Type.new(['application/x-gzip', %w(gz)]), - MIME::Type.new( - 'content-type' => 'application/gzip', - 'extensions' => 'gz', - 'registered' => true - ) + mt.add MIME::Type.new(["text/plain", %w[txt]]), + MIME::Type.new(["image/jpeg", %w[jpg jpeg]]), + MIME::Type.new("application/x-wordperfect6.1"), + MIME::Type.new( + "content-type" => "application/x-www-form-urlencoded", + "registered" => true + ), + MIME::Type.new(["application/x-gzip", %w[gz]]), + MIME::Type.new( + "content-type" => "application/gzip", + "extensions" => "gz", + "registered" => true + ) } end - describe 'is enumerable' do - it 'correctly uses an Enumerable method like #any?' do - assert(mime_types.any? { |type| type.content_type == 'text/plain' }) + describe "is enumerable" do + it "correctly uses an Enumerable method like #any?" do + assert(mime_types.any? { |type| type.content_type == "text/plain" }) end - it 'implements each with no parameters to return an Enumerator' do + it "implements each with no parameters to return an Enumerator" do assert_kind_of Enumerator, mime_types.each assert_kind_of Enumerator, mime_types.map end - it 'will create a lazy enumerator' do + it "will create a lazy enumerator" do assert_kind_of Enumerator::Lazy, mime_types.lazy assert_kind_of Enumerator::Lazy, mime_types.map.lazy end - it 'is countable with an enumerator' do + it "is countable with an enumerator" do assert_equal 6, mime_types.each.count assert_equal 6, mime_types.lazy.count end end - describe '#[]' do - it 'can be searched with a MIME::Type' do - text_plain = MIME::Type.new('text/plain') - assert_includes mime_types[text_plain], 'text/plain' + describe "#[]" do + it "can be searched with a MIME::Type" do + text_plain = MIME::Type.new("text/plain") + assert_includes mime_types[text_plain], "text/plain" assert_equal 1, mime_types[text_plain].size end - it 'can be searched with a regular expression' do - assert_includes mime_types[/plain$/], 'text/plain' + it "can be searched with a regular expression" do + assert_includes mime_types[/plain$/], "text/plain" assert_equal 1, mime_types[/plain$/].size end - it 'sorts by priority with multiple matches' do - assert_equal %w(application/gzip application/x-gzip), mime_types[/gzip$/] + it "sorts by priority with multiple matches" do + assert_equal %w[application/gzip application/x-gzip], mime_types[/gzip$/] assert_equal 2, mime_types[/gzip$/].size end - it 'can be searched with a string' do - assert_includes mime_types['text/plain'], 'text/plain' - assert_equal 1, mime_types['text/plain'].size + it "can be searched with a string" do + assert_includes mime_types["text/plain"], "text/plain" + assert_equal 1, mime_types["text/plain"].size end - it 'can be searched with the complete flag' do + it "can be searched with the complete flag" do assert_empty mime_types[ - 'application/x-www-form-urlencoded', + "application/x-www-form-urlencoded", complete: true ] - assert_includes mime_types['text/plain', complete: true], 'text/plain' - assert_equal 1, mime_types['text/plain', complete: true].size + assert_includes mime_types["text/plain", complete: true], "text/plain" + assert_equal 1, mime_types["text/plain", complete: true].size end - it 'can be searched with the registered flag' do - assert_empty mime_types['application/x-wordperfect6.1', registered: true] + it "can be searched with the registered flag" do + assert_empty mime_types["application/x-wordperfect6.1", registered: true] refute_empty mime_types[ - 'application/x-www-form-urlencoded', + "application/x-www-form-urlencoded", registered: true ] refute_empty mime_types[/gzip/, registered: true] refute_equal mime_types[/gzip/], mime_types[/gzip/, registered: true] end - it 'properly returns an empty result on a regular expression miss' do + it "properly returns an empty result on a regular expression miss" do assert_empty mime_types[/^foo/] assert_empty mime_types[/^foo/, registered: true] assert_empty mime_types[/^foo/, complete: true] end end - describe '#add' do - let(:eruby) { MIME::Type.new('application/x-eruby') } - let(:jinja) { MIME::Type.new('application/jinja2') } + describe "#add" do + let(:eruby) { MIME::Type.new("application/x-eruby") } + let(:jinja) { MIME::Type.new("application/jinja2") } - it 'successfully adds a new type' do + it "successfully adds a new type" do mime_types.add(eruby) - assert_equal mime_types['application/x-eruby'], [eruby] + assert_equal mime_types["application/x-eruby"], [eruby] end - it 'complains about adding a duplicate type' do + it "complains about adding a duplicate type" do mime_types.add(eruby) - assert_output '', /is already registered as a variant/ do + assert_output "", /is already registered as a variant/ do mime_types.add(eruby) end - assert_equal mime_types['application/x-eruby'], [eruby] + assert_equal mime_types["application/x-eruby"], [eruby] end - it 'does not complain about adding a duplicate type when quiet' do + it "does not complain about adding a duplicate type when quiet" do mime_types.add(eruby) - assert_output '', '' do + assert_output "", "" do mime_types.add(eruby, :silent) end - assert_equal mime_types['application/x-eruby'], [eruby] + assert_equal mime_types["application/x-eruby"], [eruby] end - it 'successfully adds from an array' do + it "successfully adds from an array" do mime_types.add([eruby, jinja]) - assert_equal mime_types['application/x-eruby'], [eruby] - assert_equal mime_types['application/jinja2'], [jinja] + assert_equal mime_types["application/x-eruby"], [eruby] + assert_equal mime_types["application/jinja2"], [jinja] end - it 'successfully adds from another MIME::Types' do + it "successfully adds from another MIME::Types" do mt = MIME::Types.new mt.add(mime_types) assert_equal mime_types.count, mt.count @@ -133,36 +133,36 @@ describe MIME::Types do end end - describe '#type_for' do - it 'finds all types for a given extension' do - assert_equal %w(application/gzip application/x-gzip), - mime_types.type_for('gz') + describe "#type_for" do + it "finds all types for a given extension" do + assert_equal %w[application/gzip application/x-gzip], + mime_types.type_for("gz") end - it 'separates the extension from filenames' do - assert_equal %w(image/jpeg), mime_types.of(['foo.jpeg', 'bar.jpeg']) + it "separates the extension from filenames" do + assert_equal %w[image/jpeg], mime_types.of(["foo.jpeg", "bar.jpeg"]) end - it 'finds multiple extensions' do - assert_equal %w(image/jpeg text/plain), - mime_types.type_for(%w(foo.txt foo.jpeg)) + it "finds multiple extensions" do + assert_equal %w[image/jpeg text/plain], + mime_types.type_for(%w[foo.txt foo.jpeg]) end - it 'does not find unknown extensions' do + it "does not find unknown extensions" do keys = mime_types.instance_variable_get(:@extension_index).keys - assert_empty mime_types.type_for('zzz') + assert_empty mime_types.type_for("zzz") assert_equal keys, mime_types.instance_variable_get(:@extension_index).keys end - it 'modifying type extensions causes reindexing' do - plain_text = mime_types['text/plain'].first - plain_text.add_extensions('xtxt') - assert_includes mime_types.type_for('xtxt'), 'text/plain' + it "modifying type extensions causes reindexing" do + plain_text = mime_types["text/plain"].first + plain_text.add_extensions("xtxt") + assert_includes mime_types.type_for("xtxt"), "text/plain" end end - describe '#count' do - it 'can count the number of types inside' do + describe "#count" do + it "can count the number of types inside" do assert_equal 6, mime_types.count end end diff --git a/test/test_mime_types_cache.rb b/test/test_mime_types_cache.rb index b56526f..909f18c 100644 --- a/test/test_mime_types_cache.rb +++ b/test/test_mime_types_cache.rb @@ -1,25 +1,25 @@ # frozen_string_literal: true -require 'mime/types' -require 'minitest_helper' +require "mime/types" +require "minitest_helper" + +MUTEX = Mutex.new describe MIME::Types::Cache do include Minitest::Hooks - MUTEX = Mutex.new - def around - require 'fileutils' + require "fileutils" MUTEX.synchronize do - @cache_file = File.expand_path('../cache.tst', __FILE__) - ENV['RUBY_MIME_TYPES_CACHE'] = @cache_file + @cache_file = File.expand_path("../cache.tst", __FILE__) + ENV["RUBY_MIME_TYPES_CACHE"] = @cache_file clear_cache_file super clear_cache_file - ENV.delete('RUBY_MIME_TYPES_CACHE') + ENV.delete("RUBY_MIME_TYPES_CACHE") end end @@ -32,67 +32,67 @@ describe MIME::Types::Cache do FileUtils.rm @cache_file if File.exist? @cache_file end - describe '.load' do - it 'does not use cache when RUBY_MIME_TYPES_CACHE is unset' do - ENV.delete('RUBY_MIME_TYPES_CACHE') + describe ".load" do + it "does not use cache when RUBY_MIME_TYPES_CACHE is unset" do + ENV.delete("RUBY_MIME_TYPES_CACHE") assert_nil MIME::Types::Cache.load end - it 'does not use cache when missing' do + it "does not use cache when missing" do assert_nil MIME::Types::Cache.load end - it 'registers the data to be updated by #add_extensions' do + it "registers the data to be updated by #add_extensions" do MIME::Types::Cache.save reset_mime_types - assert_equal([], MIME::Types.type_for('foo.additional')) - html = MIME::Types['text/html'][0] - html.add_extensions('additional') - assert_equal([html], MIME::Types.type_for('foo.additional')) + assert_equal([], MIME::Types.type_for("foo.additional")) + html = MIME::Types["text/html"][0] + html.add_extensions("additional") + assert_equal([html], MIME::Types.type_for("foo.additional")) end - it 'outputs an error when there is an invalid version' do + it "outputs an error when there is an invalid version" do v = MIME::Types::Data::VERSION MIME::Types::Data.send(:remove_const, :VERSION) - MIME::Types::Data.const_set(:VERSION, '0.0') + MIME::Types::Data.const_set(:VERSION, "0.0") MIME::Types::Cache.save MIME::Types::Data.send(:remove_const, :VERSION) MIME::Types::Data.const_set(:VERSION, v) MIME::Types.instance_variable_set(:@__types__, nil) - assert_output '', /MIME::Types cache: invalid version/ do - MIME::Types['text/html'] + assert_output "", /MIME::Types cache: invalid version/ do + MIME::Types["text/html"] end end - it 'outputs an error when there is a marshal file incompatibility' do + it "outputs an error when there is a marshal file incompatibility" do MIME::Types::Cache.save data = File.binread(@cache_file).reverse - File.open(@cache_file, 'wb') do |f| f.write(data) end + File.open(@cache_file, "wb") { |f| f.write(data) } MIME::Types.instance_variable_set(:@__types__, nil) - assert_output '', /incompatible marshal file format/ do - MIME::Types['text/html'] + assert_output "", /incompatible marshal file format/ do + MIME::Types["text/html"] end end end - describe '.save' do - it 'does not create cache when RUBY_MIME_TYPES_CACHE is unset' do - ENV.delete('RUBY_MIME_TYPES_CACHE') + describe ".save" do + it "does not create cache when RUBY_MIME_TYPES_CACHE is unset" do + ENV.delete("RUBY_MIME_TYPES_CACHE") assert_nil MIME::Types::Cache.save end - it 'creates the cache ' do + it "creates the cache " do assert_equal(false, File.exist?(@cache_file)) MIME::Types::Cache.save assert_equal(true, File.exist?(@cache_file)) end - it 'uses the cache' do - MIME::Types['text/html'].first.add_extensions('hex') + it "uses the cache" do + MIME::Types["text/html"].first.add_extensions("hex") MIME::Types::Cache.save MIME::Types.instance_variable_set(:@__types__, nil) - assert_includes MIME::Types['text/html'].first.extensions, 'hex' + assert_includes MIME::Types["text/html"].first.extensions, "hex" reset_mime_types end @@ -100,19 +100,19 @@ describe MIME::Types::Cache do end describe MIME::Types::Container do - it 'marshals and unmarshals correctly' do + it "marshals and unmarshals correctly" do container = MIME::Types::Container.new - container.add('xyz', 'abc') + container.add("xyz", "abc") # default proc should return Set[] - assert_equal(Set[], container['abc']) - assert_equal(Set['abc'], container['xyz']) + assert_equal(Set[], container["abc"]) + assert_equal(Set["abc"], container["xyz"]) marshalled = Marshal.dump(container) loaded_container = Marshal.load(marshalled) # default proc should still return Set[] - assert_equal(Set[], loaded_container['abc']) - assert_equal(Set['abc'], container['xyz']) + assert_equal(Set[], loaded_container["abc"]) + assert_equal(Set["abc"], container["xyz"]) end end diff --git a/test/test_mime_types_class.rb b/test/test_mime_types_class.rb index a9f4468..b47bca2 100644 --- a/test/test_mime_types_class.rb +++ b/test/test_mime_types_class.rb @@ -1,74 +1,74 @@ # frozen_string_literal: true -require 'mime/types' -require 'minitest_helper' +require "mime/types" +require "minitest_helper" -describe MIME::Types, 'registry' do +describe MIME::Types, "registry" do def setup MIME::Types.send(:load_default_mime_types) end - describe 'is enumerable' do - it 'correctly uses an Enumerable method like #any?' do - assert(MIME::Types.any? { |type| type.content_type == 'text/plain' }) + describe "is enumerable" do + it "correctly uses an Enumerable method like #any?" do + assert(MIME::Types.any? { |type| type.content_type == "text/plain" }) end - it 'implements each with no parameters to return an Enumerator' do + it "implements each with no parameters to return an Enumerator" do assert_kind_of Enumerator, MIME::Types.each assert_kind_of Enumerator, MIME::Types.map end - it 'will create a lazy enumerator' do + it "will create a lazy enumerator" do assert_kind_of Enumerator::Lazy, MIME::Types.lazy assert_kind_of Enumerator::Lazy, MIME::Types.map.lazy end - it 'is countable with an enumerator' do + it "is countable with an enumerator" do assert MIME::Types.each.count > 999 assert MIME::Types.lazy.count > 999 end end - describe '.[]' do - it 'can be searched with a MIME::Type' do - text_plain = MIME::Type.new('text/plain') - assert_includes MIME::Types[text_plain], 'text/plain' + describe ".[]" do + it "can be searched with a MIME::Type" do + text_plain = MIME::Type.new("text/plain") + assert_includes MIME::Types[text_plain], "text/plain" assert_equal 1, MIME::Types[text_plain].size end - it 'can be searched with a regular expression' do - assert_includes MIME::Types[/plain$/], 'text/plain' + it "can be searched with a regular expression" do + assert_includes MIME::Types[/plain$/], "text/plain" assert_equal 1, MIME::Types[/plain$/].size end - it 'sorts by priority with multiple matches' do + it "sorts by priority with multiple matches" do types = MIME::Types[/gzip$/].select { |t| - %w(application/gzip application/x-gzip multipart/x-gzip).include?(t) + %w[application/gzip application/x-gzip multipart/x-gzip].include?(t) } # This is this way because of a new type ending with gzip that only # appears in some data files. - assert_equal %w(application/gzip application/x-gzip multipart/x-gzip), types + assert_equal %w[application/gzip application/x-gzip multipart/x-gzip], types assert_equal 3, types.size end - it 'can be searched with a string' do - assert_includes MIME::Types['text/plain'], 'text/plain' - assert_equal 1, MIME::Types['text/plain'].size + it "can be searched with a string" do + assert_includes MIME::Types["text/plain"], "text/plain" + assert_equal 1, MIME::Types["text/plain"].size end - it 'can be searched with the complete flag' do + it "can be searched with the complete flag" do assert_empty MIME::Types[ - 'application/x-www-form-urlencoded', + "application/x-www-form-urlencoded", complete: true ] - assert_includes MIME::Types['text/plain', complete: true], 'text/plain' - assert_equal 1, MIME::Types['text/plain', complete: true].size + assert_includes MIME::Types["text/plain", complete: true], "text/plain" + assert_equal 1, MIME::Types["text/plain", complete: true].size end - it 'can be searched with the registered flag' do - assert_empty MIME::Types['application/x-wordperfect6.1', registered: true] + it "can be searched with the registered flag" do + assert_empty MIME::Types["application/x-wordperfect6.1", registered: true] refute_empty MIME::Types[ - 'application/x-www-form-urlencoded', + "application/x-www-form-urlencoded", registered: true ] refute_empty MIME::Types[/gzip/, registered: true] @@ -76,75 +76,75 @@ describe MIME::Types, 'registry' do end end - describe '.type_for' do - it 'finds all types for a given extension' do - assert_equal %w(application/gzip application/x-gzip), - MIME::Types.type_for('gz') + describe ".type_for" do + it "finds all types for a given extension" do + assert_equal %w[application/gzip application/x-gzip], + MIME::Types.type_for("gz") end - it 'separates the extension from filenames' do - assert_equal %w(image/jpeg), MIME::Types.of(['foo.jpeg', 'bar.jpeg']) + it "separates the extension from filenames" do + assert_equal %w[image/jpeg], MIME::Types.of(["foo.jpeg", "bar.jpeg"]) end - it 'finds multiple extensions' do - assert_equal %w(image/jpeg text/plain), - MIME::Types.type_for(%w(foo.txt foo.jpeg)) + it "finds multiple extensions" do + assert_equal %w[image/jpeg text/plain], + MIME::Types.type_for(%w[foo.txt foo.jpeg]) end - it 'does not find unknown extensions' do - assert_empty MIME::Types.type_for('zzz') + it "does not find unknown extensions" do + assert_empty MIME::Types.type_for("zzz") end - it 'modifying type extensions causes reindexing' do - plain_text = MIME::Types['text/plain'].first - plain_text.add_extensions('xtxt') - assert_includes MIME::Types.type_for('xtxt'), 'text/plain' + it "modifying type extensions causes reindexing" do + plain_text = MIME::Types["text/plain"].first + plain_text.add_extensions("xtxt") + assert_includes MIME::Types.type_for("xtxt"), "text/plain" end end - describe '.count' do - it 'can count the number of types inside' do + describe ".count" do + it "can count the number of types inside" do assert MIME::Types.count > 999 end end - describe '.add' do + describe ".add" do def setup MIME::Types.instance_variable_set(:@__types__, nil) MIME::Types.send(:load_default_mime_types) end - let(:eruby) { MIME::Type.new('application/x-eruby') } - let(:jinja) { MIME::Type.new('application/jinja2') } + let(:eruby) { MIME::Type.new("application/x-eruby") } + let(:jinja) { MIME::Type.new("application/jinja2") } - it 'successfully adds a new type' do + it "successfully adds a new type" do MIME::Types.add(eruby) - assert_equal MIME::Types['application/x-eruby'], [eruby] + assert_equal MIME::Types["application/x-eruby"], [eruby] end - it 'complains about adding a duplicate type' do + it "complains about adding a duplicate type" do MIME::Types.add(eruby) - assert_output '', /is already registered as a variant/ do + assert_output "", /is already registered as a variant/ do MIME::Types.add(eruby) end - assert_equal MIME::Types['application/x-eruby'], [eruby] + assert_equal MIME::Types["application/x-eruby"], [eruby] end - it 'does not complain about adding a duplicate type when quiet' do + it "does not complain about adding a duplicate type when quiet" do MIME::Types.add(eruby) assert_silent do MIME::Types.add(eruby, :silent) end - assert_equal MIME::Types['application/x-eruby'], [eruby] + assert_equal MIME::Types["application/x-eruby"], [eruby] end - it 'successfully adds from an array' do + it "successfully adds from an array" do MIME::Types.add([eruby, jinja]) - assert_equal MIME::Types['application/x-eruby'], [eruby] - assert_equal MIME::Types['application/jinja2'], [jinja] + assert_equal MIME::Types["application/x-eruby"], [eruby] + assert_equal MIME::Types["application/jinja2"], [jinja] end - it 'successfully adds from another MIME::Types' do + it "successfully adds from another MIME::Types" do old_count = MIME::Types.count mt = MIME::Types.new diff --git a/test/test_mime_types_lazy.rb b/test/test_mime_types_lazy.rb index 12233c0..04f81f6 100644 --- a/test/test_mime_types_lazy.rb +++ b/test/test_mime_types_lazy.rb @@ -1,16 +1,16 @@ # frozen_string_literal: true -require 'mime/types' -require 'minitest_helper' +require "mime/types" +require "minitest_helper" -describe MIME::Types, 'lazy loading' do +describe MIME::Types, "lazy loading" do def setup - ENV['RUBY_MIME_TYPES_LAZY_LOAD'] = 'true' + ENV["RUBY_MIME_TYPES_LAZY_LOAD"] = "true" end def teardown reset_mime_types - ENV.delete('RUBY_MIME_TYPES_LAZY_LOAD') + ENV.delete("RUBY_MIME_TYPES_LAZY_LOAD") end def reset_mime_types @@ -18,32 +18,32 @@ describe MIME::Types, 'lazy loading' do MIME::Types.send(:load_default_mime_types) end - describe '.lazy_load?' do - it 'is true when RUBY_MIME_TYPES_LAZY_LOAD is set' do - assert_output '', /RUBY_MIME_TYPES_LAZY_LOAD/ do + describe ".lazy_load?" do + it "is true when RUBY_MIME_TYPES_LAZY_LOAD is set" do + assert_output "", /RUBY_MIME_TYPES_LAZY_LOAD/ do assert_equal true, MIME::Types.send(:lazy_load?) end end - it 'is nil when RUBY_MIME_TYPES_LAZY_LOAD is unset' do - ENV['RUBY_MIME_TYPES_LAZY_LOAD'] = nil - assert_output '', '' do + it "is nil when RUBY_MIME_TYPES_LAZY_LOAD is unset" do + ENV["RUBY_MIME_TYPES_LAZY_LOAD"] = nil + assert_output "", "" do assert_nil MIME::Types.send(:lazy_load?) end end - it 'is false when RUBY_MIME_TYPES_LAZY_LOAD is false' do - ENV['RUBY_MIME_TYPES_LAZY_LOAD'] = 'false' - assert_output '', /RUBY_MIME_TYPES_LAZY_LOAD/ do + it "is false when RUBY_MIME_TYPES_LAZY_LOAD is false" do + ENV["RUBY_MIME_TYPES_LAZY_LOAD"] = "false" + assert_output "", /RUBY_MIME_TYPES_LAZY_LOAD/ do assert_equal false, MIME::Types.send(:lazy_load?) end end end - it 'loads lazily when RUBY_MIME_TYPES_LAZY_LOAD is set' do + it "loads lazily when RUBY_MIME_TYPES_LAZY_LOAD is set" do MIME::Types.instance_variable_set(:@__types__, nil) assert_nil MIME::Types.instance_variable_get(:@__types__) - refute_nil MIME::Types['text/html'].first + refute_nil MIME::Types["text/html"].first refute_nil MIME::Types.instance_variable_get(:@__types__) end end diff --git a/test/test_mime_types_loader.rb b/test/test_mime_types_loader.rb index 7fb4e9b..af5d851 100644 --- a/test/test_mime_types_loader.rb +++ b/test/test_mime_types_loader.rb @@ -1,32 +1,32 @@ # frozen_string_literal: true -require 'mime/types' -require 'minitest_helper' +require "mime/types" +require "minitest_helper" describe MIME::Types::Loader do def setup - @path = File.expand_path('../fixture', __FILE__) - @loader = MIME::Types::Loader.new(@path) - @bad_path = File.expand_path('../bad-fixtures', __FILE__) + @path = File.expand_path("../fixture", __FILE__) + @loader = MIME::Types::Loader.new(@path) + @bad_path = File.expand_path("../bad-fixtures", __FILE__) end def assert_correctly_loaded(types) - assert_includes(types, 'application/1d-interleaved-parityfec') - assert_equal(%w(webm), types['audio/webm'].first.extensions) - refute(types['audio/webm'].first.registered?) + assert_includes(types, "application/1d-interleaved-parityfec") + assert_equal(%w[webm], types["audio/webm"].first.extensions) + refute(types["audio/webm"].first.registered?) - assert_equal('Fixes a bug with IE6 and progressive JPEGs', - types['image/pjpeg'].first.docs) + assert_equal("Fixes a bug with IE6 and progressive JPEGs", + types["image/pjpeg"].first.docs) - assert(types['audio/vnd.qcelp'].first.obsolete?) - assert_equal('audio/QCELP', types['audio/vnd.qcelp'].first.use_instead) + assert(types["audio/vnd.qcelp"].first.obsolete?) + assert_equal("audio/QCELP", types["audio/vnd.qcelp"].first.use_instead) end - it 'loads YAML files correctly' do + it "loads YAML files correctly" do assert_correctly_loaded @loader.load_yaml end - it 'loads JSON files correctly' do + it "loads JSON files correctly" do assert_correctly_loaded @loader.load_json end end |