Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

some improvements #356

Merged
merged 3 commits into from
Mar 17, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 2 additions & 5 deletions .rubocop_todo.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ Metrics/AbcSize:
# Offense count: 1
# Configuration parameters: CountComments.
Metrics/ClassLength:
Max: 353
Max: 230

# Offense count: 6
Metrics/CyclomaticComplexity:
Expand All @@ -32,7 +32,7 @@ Metrics/MethodLength:
# Offense count: 1
# Configuration parameters: CountComments.
Metrics/ModuleLength:
Max: 394
Max: 200

# Offense count: 4
Metrics/PerceivedComplexity:
Expand All @@ -51,7 +51,6 @@ Style/Documentation:
# Offense count: 2
Style/DoubleNegation:
Exclude:
- 'lib/grape-swagger/doc_methods.rb'

# Offense count: 3
# Configuration parameters: Exclude.
Expand All @@ -65,12 +64,10 @@ Style/FileName:
# Configuration parameters: NamePrefix, NamePrefixBlacklist.
Style/PredicateName:
Exclude:
- 'lib/grape-swagger/doc_methods.rb'

# Offense count: 4
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle, SupportedStyles, AllowInnerSlashes.
Style/RegexpLiteral:
Exclude:
- 'lib/grape-swagger.rb'
- 'lib/grape-swagger/doc_methods.rb'
15 changes: 14 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,18 @@
n.n.n / 2016-02-14

n.n.n / 2016-03-16
==================
[#356](https://github.com/ruby-grape/grape-swagger/pull/356)

- adds `consumes` setting
- refactoring

[#354](https://github.com/ruby-grape/grape-swagger/pull/354) some improvements

- fixes setting of `base_path` and `host`;
- adds possibility to configure the setting of `version` and `base_path` in documented path;
- adds `operationId`

[#353](https://github.com/ruby-grape/grape-swagger/pull/353) resolves issue #352

### 0.10.4 (Next)

Expand Down
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,7 @@ end
## Configure

[host](#host)
[base_path](#base_path)
[mount_path](#mount_path)
[add_base_path](#add_base_path)
[add_version](#add_version)
Expand Down Expand Up @@ -337,6 +338,8 @@ desc 'Get all kittens!', {
entity: Entities::Kitten, # or success
http_codes: [[401, 'KittenBitesError', Entities::BadKitten]] # or failure
# also explicit as hash: [{ code: 401, mssage: 'KittenBitesError', model: Entities::BadKitten }]
produces: [ "array", "of", "mime_types" ],
consumes: [ "array", "of", "mime_types" ]
}
get '/kittens' do
```
Expand Down
11 changes: 10 additions & 1 deletion lib/grape-swagger.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,19 @@
require 'grape-swagger/version'
require 'grape-swagger/endpoint'
require 'grape-swagger/errors'
require 'grape-swagger/doc_methods/produces'

# TODO: loading should be simplified by using a better/more clever dependincy structure
require 'grape-swagger/doc_methods/produces_consumes'
require 'grape-swagger/doc_methods/data_type'
require 'grape-swagger/doc_methods/extensions'
require 'grape-swagger/doc_methods/operation_id'
require 'grape-swagger/doc_methods/optional_object'
require 'grape-swagger/doc_methods/path_string'
require 'grape-swagger/doc_methods/tag_name_description'
require 'grape-swagger/doc_methods/parse_params'

require 'grape-swagger/doc_methods'

require 'grape-swagger/markdown/kramdown_adapter'
require 'grape-swagger/markdown/redcarpet_adapter'

Expand Down
23 changes: 23 additions & 0 deletions lib/grape-swagger/doc_methods/operation_id.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
module GrapeSwagger
module DocMethods
class OperationId
class << self
def build(method, path = nil)
verb = method.to_s.downcase

unless path.nil?
operation = path.split('/').map(&:capitalize).join
operation.gsub!(/\-(\w)/, &:upcase).delete!('-') if operation.include?('-')
operation.gsub!(/\_(\w)/, &:upcase).delete!('_') if operation.include?('_')
if path.include?('{')
operation.gsub!(/\{(\w)/, &:upcase)
operation.delete!('{').delete!('}')
end
end

"#{verb}#{operation}"
end
end
end
end
end
15 changes: 15 additions & 0 deletions lib/grape-swagger/doc_methods/optional_object.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
module GrapeSwagger
module DocMethods
class OptionalObject
class << self
def build(key, options, request = nil)
if options[key]
options[key].is_a?(Proc) ? options[key].call : options[key]
else
request
end
end
end
end
end
end
102 changes: 102 additions & 0 deletions lib/grape-swagger/doc_methods/parse_params.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
module GrapeSwagger
module DocMethods
class ParseParams
class << self
def call(param, value, route)
@array_items = {}
path = route.route_path
method = route.route_method

additional_documentation = value.is_a?(Hash) ? value[:documentation] : nil
data_type = GrapeSwagger::DocMethods::DataType.call(value)

if additional_documentation && value.is_a?(Hash)
value = additional_documentation.merge(value)
end

description = value.is_a?(Hash) ? value[:desc] || value[:description] : nil
required = value.is_a?(Hash) ? value[:required] : false
default_value = value.is_a?(Hash) ? value[:default] : nil
example = value.is_a?(Hash) ? value[:example] : nil
is_array = value.is_a?(Hash) ? (value[:is_array] || false) : false
values = value.is_a?(Hash) ? value[:values] : nil
name = (value.is_a?(Hash) && value[:full_name]) || param
enum_or_range_values = parse_enum_or_range_values(values)

value_type = { value: value, data_type: data_type, path: path }

parsed_params = {
in: param_type(value_type, param, method, is_array),
name: name,
description: description,
type: data_type,
required: required,
allowMultiple: is_array
}

if GrapeSwagger::DocMethods::DataType::PRIMITIVE_MAPPINGS.key?(data_type)
parsed_params[:type], parsed_params[:format] = GrapeSwagger::DocMethods::DataType::PRIMITIVE_MAPPINGS[data_type]
end

parsed_params[:items] = @array_items if @array_items.present?

parsed_params[:defaultValue] = example if example
parsed_params[:defaultValue] = default_value if default_value && example.blank?

parsed_params.merge!(enum_or_range_values) if enum_or_range_values
parsed_params
end

def primitive?(type)
%w(object integer long float double string byte boolean date datetime).include? type.to_s.downcase
end

private

def param_type(value_type, param, method, is_array)
# TODO: use `value_type.dig():value, :documentation, :param_type)` instead req ruby2.3
#
if value_type[:value].is_a?(Hash) &&
value_type[:value].key?(:documentation) &&
value_type[:value][:documentation].key?(:param_type)

if is_array
@array_items = { 'type' => value_type[:data_type] }

'array'
end
else
case
when value_type[:path].include?("{#{param}}")
'path'
when %w(POST PUT PATCH).include?(method)
primitive?(value_type[:data_type]) ? 'formData' : 'body'
else
'query'
end
end
end

def parse_enum_or_range_values(values)
case values
when Range
parse_range_values(values) if values.first.is_a?(Integer)
when Proc
values_result = values.call
if values_result.is_a?(Range) && values_result.first.is_a?(Integer)
parse_range_values(values_result)
else
{ enum: values_result }
end
else
{ enum: values } if values
end
end

def parse_range_values(values)
{ minimum: values.first, maximum: values.last }
end
end
end
end
end
29 changes: 29 additions & 0 deletions lib/grape-swagger/doc_methods/path_string.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
module GrapeSwagger
module DocMethods
class PathString
class << self
def build(path, options = {})
# always removing format
path.sub!(/\(\.\w+?\)$/, '')
path.sub!('(.:format)', '')

# ... format path params
path.gsub!(/:(\w+)/, '{\1}')

# set item from path, this could be used for the definitions object
item = path.gsub(%r{/{(.+?)}}, '').split('/').last.singularize.underscore.camelize || 'Item'

if options[:version] && options[:add_version]
path.sub!('{version}', options[:version])
else
path.sub!('/{version}', '')
end

path = "#{GrapeSwagger::DocMethods::OptionalObject.build(:base_path, options)}#{path}" if options[:add_base_path]

[item, path.start_with?('/') ? path : "/#{path}"]
end
end
end
end
end
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
module GrapeSwagger
module DocMethods
class Produces
class ProducesConsumes
class << self
def call(*args)
return ['application/json'] unless args.flatten.present?
Expand Down
26 changes: 26 additions & 0 deletions lib/grape-swagger/doc_methods/tag_name_description.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
module GrapeSwagger
module DocMethods
class TagNameDescription
class << self
def build(options = {})
target_class = options[:target_class]
namespaces = target_class.combined_namespaces
namespace_routes = target_class.combined_namespace_routes

namespace_routes.keys.map do |local_route|
next if namespace_routes[local_route].map(&:route_hidden).all? { |value| value.respond_to?(:call) ? value.call : value }

original_namespace_name = target_class.combined_namespace_identifiers.key?(local_route) ? target_class.combined_namespace_identifiers[local_route] : local_route
description = namespaces[original_namespace_name] && namespaces[original_namespace_name].options[:desc]
description ||= "Operations about #{original_namespace_name.pluralize}"

{
name: local_route,
description: description
}
end.compact
end
end
end
end
end
Loading