Class: Praxis::ActionDefinition

Inherits:
Object
  • Object
show all
Defined in:
lib/praxis.rb,
lib/praxis/action_definition.rb,
lib/praxis/action_definition/headers_dsl_compiler.rb

Defined Under Namespace

Classes: HeadersDSLCompiler

Class Attribute Summary collapse

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, resource_definition, **opts, &block) ⇒ ActionDefinition

Returns a new instance of ActionDefinition.



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/praxis/action_definition.rb', line 35

def initialize(name, resource_definition, **opts, &block)
  @name = name
  @resource_definition = resource_definition
  @responses = Hash.new
  @metadata = Hash.new
  @routes = []
  @traits = []

  if (media_type = resource_definition.media_type)
    if media_type.kind_of?(Class) && media_type < Praxis::Types::MediaTypeCommon
      @reference_media_type = media_type
    end
  end

  version = resource_definition.version
  api_info = ApiDefinition.instance.info(resource_definition.version)

  route_base = "#{api_info.base_path}#{resource_definition.version_prefix}"
  prefix = Array(resource_definition.routing_prefix)

  @routing_config = RoutingConfig.new(version: version, base: route_base, prefix: prefix)

  resource_definition.traits.each do |trait|
    self.trait(trait)
  end

  resource_definition.action_defaults.apply!(self)

  self.instance_eval(&block) if block_given?
end

Class Attribute Details

.doc_decorationsObject

Returns the value of attribute doc_decorations.



26
27
28
# File 'lib/praxis/action_definition.rb', line 26

def doc_decorations
  @doc_decorations
end

Instance Attribute Details

#metadataObject (readonly)

opaque hash of user-defined medata, used to decorate the definition, and also available in the generated JSON documents



23
24
25
# File 'lib/praxis/action_definition.rb', line 23

def 
  @metadata
end

#nameObject (readonly)

Returns the value of attribute name.



13
14
15
# File 'lib/praxis/action_definition.rb', line 13

def name
  @name
end

#named_routesObject (readonly)

Returns the value of attribute named_routes.



17
18
19
# File 'lib/praxis/action_definition.rb', line 17

def named_routes
  @named_routes
end

#primary_routeObject (readonly)

Returns the value of attribute primary_route.



16
17
18
# File 'lib/praxis/action_definition.rb', line 16

def primary_route
  @primary_route
end

#resource_definitionObject (readonly)

Returns the value of attribute resource_definition.



14
15
16
# File 'lib/praxis/action_definition.rb', line 14

def resource_definition
  @resource_definition
end

#responsesObject (readonly)

Returns the value of attribute responses.



18
19
20
# File 'lib/praxis/action_definition.rb', line 18

def responses
  @responses
end

#routesObject (readonly)

Returns the value of attribute routes.



15
16
17
# File 'lib/praxis/action_definition.rb', line 15

def routes
  @routes
end

#traitsObject (readonly)

Returns the value of attribute traits.



19
20
21
# File 'lib/praxis/action_definition.rb', line 19

def traits
  @traits
end

Class Method Details

.decorate_docs(&callback) ⇒ Object



31
32
33
# File 'lib/praxis/action_definition.rb', line 31

def self.decorate_docs(&callback)
  self.doc_decorations << callback
end

.url_description(route:, params_example:, params:) ⇒ Object



204
205
206
207
208
209
210
211
212
213
214
215
216
# File 'lib/praxis/action_definition.rb', line 204

def self.url_description(route:, params_example:, params:)
  route_description = route.describe

  example_hash = params_example ? params_example.dump : {}
  hash = route.example(example_hash: example_hash, params: params)

  query_string = URI.encode_www_form(hash[:query_params])
  url = hash[:url]
  url = [url,query_string].join('?') unless query_string.empty?

  route_description[:example] = url
  route_description
end

Instance Method Details

#create_attribute(type = Attributor::Struct, **opts, &block) ⇒ Object



97
98
99
100
101
102
103
# File 'lib/praxis/action_definition.rb', line 97

def create_attribute(type=Attributor::Struct, **opts, &block)
  unless opts.key?(:reference)
    opts[:reference] = @reference_media_type if @reference_media_type && block
  end

  return Attributor::Attribute.new(type, opts, &block)
end

#derive_content_type(example, handler_name) ⇒ Object

Determine the content_type to report for a given example, using handler_name if possible.

Considers any pre-defined set of values on the content_type attributge of the headers.



294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
# File 'lib/praxis/action_definition.rb', line 294

def derive_content_type(example, handler_name)
  # MultipartArrays *must* use the provided content_type
  if example.kind_of? Praxis::Types::MultipartArray
    return MediaTypeIdentifier.load(example.content_type)
  end

   _, content_type_attribute = self.headers && self.headers.attributes.find { |k,v| k.to_s =~ /^content[-_]{1}type$/i }
  if content_type_attribute && content_type_attribute.options.key?(:values)

    # if any defined value match the preferred handler_name, return it
    content_type_attribute.options[:values].each do |ct|
      mti = MediaTypeIdentifier.load(ct)
      return mti if mti.handler_name == handler_name
    end

    # otherwise, pick the first
    pick = MediaTypeIdentifier.load(content_type_attribute.options[:values].first)

    # and return that one if it already corresponds to a registered handler
    # otherwise, add the encoding
    if Praxis::Application.instance.handlers.include?(pick.handler_name)
      return pick
    else
      return pick + handler_name
    end
  end

  # generic default encoding
  MediaTypeIdentifier.load("application/#{handler_name}")
end

#describe(context: nil) ⇒ Object



218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
# File 'lib/praxis/action_definition.rb', line 218

def describe(context: nil)
  {}.tap do |hash|
    hash[:description] = description
    hash[:name] = name
    hash[:metadata] = 
    if headers
      headers_example = headers.example(context)
      hash[:headers] = headers_description(example: headers_example)
    end
    if params
      params_example = params.example(context)
      hash[:params] = params_description(example: params_example)
    end
    if payload
      payload_example = payload.example(context)

      hash[:payload] = payload_description(example: payload_example)
    end

    hash[:responses] = responses.inject({}) do |memo, (response_name, response)|
      memo[response.name] = response.describe(context: context)
      memo
    end
    hash[:traits] = traits if traits.any?
    # FIXME: change to :routes along with api browser
    hash[:urls] = routes.collect do |route|
      ActionDefinition.url_description(route: route, params: self.params, params_example: params_example)
    end.compact
    self.class.doc_decorations.each do |callback|
      callback.call(self, hash)
    end
  end
end

#description(text = nil) ⇒ Object



199
200
201
202
# File 'lib/praxis/action_definition.rb', line 199

def description(text = nil)
  @description = text if text
  @description
end

#headers(type = nil, **opts, &block) ⇒ Object



153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
# File 'lib/praxis/action_definition.rb', line 153

def headers(type=nil, **opts, &block)
  return @headers unless block

  unless( opts.key? :required )
    opts[:required] = true # Make the payload required by default
  end

  if @headers
    update_attribute(@headers, opts, block)
  else
    type = Attributor::Hash.of(key:String) unless type
    @headers = create_attribute(type,
                                dsl_compiler: HeadersDSLCompiler, case_insensitive_load: true,
                                **opts, &block)

    @headers
  end
  @precomputed_header_keys_for_rack = nil #clear memoized data
end

#headers_description(example:) ⇒ Object



252
253
254
255
256
257
258
259
# File 'lib/praxis/action_definition.rb', line 252

def headers_description(example: )
  output = headers.describe(example: example)
  required_headers = self.headers.attributes.select{|k,attr| attr.options && attr.options[:required] == true  }
  output[:example] = required_headers.each_with_object({}) do | (name, attr), hash |
    hash[name] = example[name].to_s # Some simple types (like Boolean) can be used as header values, but must convert back to s
  end
  output
end

#nodoc!Object



357
358
359
# File 'lib/praxis/action_definition.rb', line 357

def nodoc!
  [:doc_visibility] = :none
end

#params(type = Attributor::Struct, **opts, &block) ⇒ Object



105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
# File 'lib/praxis/action_definition.rb', line 105

def params(type=Attributor::Struct, **opts, &block)
  return @params if !block && ( opts.nil? || opts.empty? ) && type == Attributor::Struct

  unless( opts.key? :required )
    opts[:required] = true # Make the payload required by default
  end

  if @params
    unless type == Attributor::Struct && @params.type < Attributor::Struct
      raise Exceptions::InvalidConfiguration.new(
        "Invalid type received for extending params: #{type.name}"
      )
    end
    update_attribute(@params, opts, block)
  else
    @params = create_attribute(type, **opts, &block)
    if (api_info = ApiDefinition.instance.info(resource_definition.version))
      if api_info.base_params
        base_attrs = api_info.base_params.attributes
        @params.attributes.merge!(base_attrs) do |key, oldval, newval|
          oldval
        end
      end
    end
  end

  @params
end

#params_description(example:) ⇒ Object



261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
# File 'lib/praxis/action_definition.rb', line 261

def params_description(example:)
  route_params = []
  if primary_route.nil?
    warn "Warning: No routes defined for #{resource_definition.name}##{name}."
  else
    route_params = primary_route.path.
      named_captures.
      keys.
      collect(&:to_sym)
  end

  desc = params.describe(example: example)
  desc[:type][:attributes].keys.each do |k|
    source = if route_params.include? k
      'url'
    else
      'query'
    end
    desc[:type][:attributes][k][:source] = source
  end
  required_params = desc[:type][:attributes].select{|k,v| v[:source] == 'query' && v[:required] == true }.keys
  phash = required_params.each_with_object({}) do | name, hash |
    hash[name] = example[name]
  end
  desc[:example] = URI.encode_www_form(phash)
  desc
end

#payload(type = Attributor::Struct, **opts, &block) ⇒ Object



134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
# File 'lib/praxis/action_definition.rb', line 134

def payload(type=Attributor::Struct, **opts, &block)
  return @payload if !block && ( opts.nil? || opts.empty? ) && type == Attributor::Struct

  unless( opts.key? :required )
    opts[:required] = true # Make the payload required by default
  end

  if @payload
    unless type == Attributor::Struct && @payload.type < Attributor::Struct
      raise Exceptions::InvalidConfiguration.new(
        "Invalid type received for extending params: #{type.name}"
      )
    end
    update_attribute(@payload, opts, block)
  else
    @payload = create_attribute(type, **opts, &block)
  end
end

#payload_description(example:) ⇒ Object



326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
# File 'lib/praxis/action_definition.rb', line 326

def payload_description(example:)
  hash = payload.describe(example: example)

  hash[:examples] = {}

  default_handlers = ApiDefinition.instance.info.consumes

  default_handlers.each do |default_handler|
    dumped_payload = payload.dump(example, default_format: default_handler)

    content_type = derive_content_type(example, default_handler)
    handler = Praxis::Application.instance.handlers[content_type.handler_name]

    # in case handler is nil, use dumped_payload as-is.
    generated_payload = if handler.nil?
      dumped_payload
    else
      handler.generate(dumped_payload)
    end


    hash[:examples][default_handler] = {
      content_type: content_type.to_s,
      body: generated_payload
    }
  end

  hash
end

#precomputed_header_keys_for_rackObject

Good optimization to avoid creating lots of strings and comparisons on a per-request basis. However, this is hacky, as it is rack-specific, and does not really belong here



176
177
178
179
180
181
182
183
184
# File 'lib/praxis/action_definition.rb', line 176

def precomputed_header_keys_for_rack
  @precomputed_header_keys_for_rack ||= begin
    @headers.attributes.keys.each_with_object(Hash.new) do |key,hash|
      name = key.to_s
      name = "HTTP_#{name.gsub('-','_').upcase}" unless ( name == "CONTENT_TYPE" || name == "CONTENT_LENGTH" )
      hash[name] = key
    end
  end
end

#response(name, type = nil, **args, &block) ⇒ Object



82
83
84
85
86
87
88
89
90
91
92
93
94
95
# File 'lib/praxis/action_definition.rb', line 82

def response(name, type=nil, **args, &block)
  if type
    # should verify type is a media type

    if block_given?
      type = type.construct(block)
    end

    args[:media_type] = type
  end

  template = ApiDefinition.instance.response(name)
  @responses[name] = template.compile(self, **args)
end

#routing(&block) ⇒ Object



187
188
189
190
191
192
193
194
195
196
# File 'lib/praxis/action_definition.rb', line 187

def routing(&block)
  @routing_config.instance_eval &block

  @routes = @routing_config.routes
  @primary_route = @routing_config.routes.first
  @named_routes = @routing_config.routes.each_with_object({}) do |route, hash|
    next if route.name.nil?
    hash[route.name] = route
  end
end

#trait(trait_name) ⇒ Object Also known as: use



66
67
68
69
70
71
72
73
74
# File 'lib/praxis/action_definition.rb', line 66

def trait(trait_name)
  unless ApiDefinition.instance.traits.has_key? trait_name
    raise Exceptions::InvalidTrait.new("Trait #{trait_name} not found in the system")
  end

  trait = ApiDefinition.instance.traits.fetch(trait_name)
  trait.apply!(self)
  traits << trait_name
end

#update_attribute(attribute, options, block) ⇒ Object



77
78
79
80
# File 'lib/praxis/action_definition.rb', line 77

def update_attribute(attribute, options, block)
  attribute.options.merge!(options)
  attribute.type.attributes(options, &block)
end