lib/grape-swagger/entity/parser.rb in grape-swagger-entity-0.1.6 vs lib/grape-swagger/entity/parser.rb in grape-swagger-entity-0.2.0

- old
+ new

@@ -8,38 +8,34 @@ @model = model @endpoint = endpoint end def call - # TODO: this should only be a temporary hack ;) - if ::GrapeEntity::VERSION =~ /0\.4\.\d/ - warn 'usage of grape-entity <0.5.0 is deprecated' - parameters = model.exposures ? model.exposures : model.documentation - else - parameters = model.root_exposures.each_with_object({}) do |value, memo| - memo[value.attribute] = value.send(:options) - end + parameters = model.root_exposures.each_with_object({}) do |value, memo| + memo[value.attribute] = value.send(:options) end parse_grape_entity_params(parameters) end private - def parse_grape_entity_params(params) + def parse_grape_entity_params(params, parent_model = nil) return unless params params.each_with_object({}) do |(entity_name, entity_options), memo| next if entity_options.fetch(:documentation, {}).fetch(:in, nil).to_s == 'header' entity_name = entity_options[:as] if entity_options[:as] documentation = entity_options[:documentation] - model = model_from(entity_options) + entity_model = model_from(entity_options) - if model - name = endpoint.nil? ? model.to_s.demodulize : endpoint.send(:expose_params_from_model, model) + if entity_model + name = endpoint.nil? ? entity_model.to_s.demodulize : endpoint.send(:expose_params_from_model, entity_model) memo[entity_name] = entity_model_type(name, entity_options) + elsif entity_options[:nesting] + memo[entity_name] = parse_nested(entity_name, entity_options, parent_model) else memo[entity_name] = data_type_from(entity_options) next unless documentation memo[entity_name][:default] = documentation[:default] if documentation[:default] @@ -66,9 +62,42 @@ if could_it_be_a_model?(entity_options[:documentation]) model ||= entity_options[:documentation][:type] end model + end + + def parse_nested(entity_name, entity_options, parent_model = nil) + nested_entity = if parent_model.nil? + model.root_exposures.find_by(entity_name) + else + parent_model.nested_exposures.find_by(entity_name) + end + + params = nested_entity.nested_exposures.each_with_object({}) do |value, memo| + memo[value.attribute] = value.send(:options) + end + + properties = parse_grape_entity_params(params, nested_entity) + is_a_collection = entity_options[:documentation].is_a?(Hash) && + entity_options[:documentation][:type].to_s.casecmp('array').zero? + + if is_a_collection + { + type: :array, + items: { + type: :object, + properties: properties + }, + description: entity_options[:desc] || '' + } + else + { + type: :object, + properties: properties, + description: entity_options[:desc] || '' + } + end end def could_it_be_a_model?(value) return false if value.nil? direct_model_type?(value[:type]) || ambiguous_model_type?(value[:type])