lib/grape/path.rb in grape-2.0.0 vs lib/grape/path.rb in grape-2.1.0
- old
+ new
@@ -1,16 +1,10 @@
# frozen_string_literal: true
-require 'grape/util/cache'
-
module Grape
# Represents a path to an endpoint.
class Path
- def self.prepare(raw_path, namespace, settings)
- Path.new(raw_path, namespace, settings)
- end
-
attr_reader :raw_path, :namespace, :settings
def initialize(raw_path, namespace, settings)
@raw_path = raw_path
@namespace = namespace
@@ -20,35 +14,31 @@
def mount_path
settings[:mount_path]
end
def root_prefix
- split_setting(:root_prefix)
+ settings[:root_prefix]
end
def uses_specific_format?
- if settings.key?(:format) && settings.key?(:content_types)
- (settings[:format] && Array(settings[:content_types]).size == 1)
- else
- false
- end
+ return false unless settings.key?(:format) && settings.key?(:content_types)
+
+ settings[:format] && Array(settings[:content_types]).size == 1
end
def uses_path_versioning?
- if settings.key?(:version) && settings[:version_options] && settings[:version_options].key?(:using)
- (settings[:version] && settings[:version_options][:using] == :path)
- else
- false
- end
+ return false unless settings.key?(:version) && settings[:version_options]&.key?(:using)
+
+ settings[:version] && settings[:version_options][:using] == :path
end
def namespace?
- namespace&.match?(/^\S/) && namespace != '/'
+ namespace&.match?(/^\S/) && not_slash?(namespace)
end
def path?
- raw_path&.match?(/^\S/) && raw_path != '/'
+ raw_path&.match?(/^\S/) && not_slash?(raw_path)
end
def suffix
if uses_specific_format?
"(.#{settings[:format]})"
@@ -58,11 +48,11 @@
'(/.:format)'
end
end
def path
- Grape::Router.normalize_path(PartsCache[parts])
+ PartsCache[parts]
end
def path_with_suffix
"#{path}#{suffix}"
end
@@ -73,26 +63,31 @@
private
class PartsCache < Grape::Util::Cache
def initialize
+ super
@cache = Hash.new do |h, parts|
- h[parts] = -parts.join('/')
+ h[parts] = Grape::Router.normalize_path(parts.join('/'))
end
end
end
def parts
- parts = [mount_path, root_prefix].compact
- parts << ':version' if uses_path_versioning?
- parts << namespace.to_s
- parts << raw_path.to_s
- parts.flatten.reject { |part| part == '/' }
+ [].tap do |parts|
+ add_part(parts, mount_path)
+ add_part(parts, root_prefix)
+ parts << ':version' if uses_path_versioning?
+ add_part(parts, namespace)
+ add_part(parts, raw_path)
+ end
end
- def split_setting(key)
- return if settings[key].nil?
+ def add_part(parts, value)
+ parts << value if value && not_slash?(value)
+ end
- settings[key].to_s.split('/')
+ def not_slash?(value)
+ value != '/'
end
end
end