Class: HaveAPI::Action

Inherits:
Common
  • Object
show all
Includes:
Hookable
Defined in:
lib/haveapi/action.rb

Class Attribute Summary collapse

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Hookable

included

Methods inherited from Common

check_build, has_attr, inherit_attrs

Constructor Details

#initialize(request, version, params, body, context) ⇒ Action

Returns a new instance of Action.



232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
# File 'lib/haveapi/action.rb', line 232

def initialize(request, version, params, body, context)
  @request = request
  @version = version
  @params = params
  @params.update(body) if body
  @context = context
  @context.action = self.class
  @context.action_instance = self
   = {}
  @reply_meta = {object: {}, global: {}}
  @flags = {}

  class_auth = self.class.authorization

  if class_auth
    @authorization = class_auth.clone
  else
    @authorization = Authorization.new {}
  end
end

Class Attribute Details

.authorizationObject (readonly)

Returns the value of attribute authorization.



29
30
31
# File 'lib/haveapi/action.rb', line 29

def authorization
  @authorization
end

.examplesObject (readonly)

Returns the value of attribute examples.



29
30
31
# File 'lib/haveapi/action.rb', line 29

def examples
  @examples
end

.resourceObject (readonly)

Returns the value of attribute resource.



29
30
31
# File 'lib/haveapi/action.rb', line 29

def resource
  @resource
end

Instance Attribute Details

#errorsObject (readonly)

Returns the value of attribute errors.



25
26
27
# File 'lib/haveapi/action.rb', line 25

def errors
  @errors
end

#flagsObject

Returns the value of attribute flags.



26
27
28
# File 'lib/haveapi/action.rb', line 26

def flags
  @flags
end

#messageObject (readonly)

Returns the value of attribute message.



25
26
27
# File 'lib/haveapi/action.rb', line 25

def message
  @message
end

#versionObject (readonly)

Returns the value of attribute version.



25
26
27
# File 'lib/haveapi/action.rb', line 25

def version
  @version
end

Class Method Details

.authorize(&block) ⇒ Object



153
154
155
# File 'lib/haveapi/action.rb', line 153

def authorize(&block)
  @authorization = Authorization.new(&block)
end

.build_route(prefix) ⇒ Object



164
165
166
167
168
169
170
171
172
# File 'lib/haveapi/action.rb', line 164

def build_route(prefix)
  route = @route || to_s.demodulize.underscore

  if !route.is_a?(String) && route.respond_to?(:call)
    route = route.call(self.resource)
  end

  prefix + route % {resource: self.resource.to_s.demodulize.underscore}
end

.delayed_inherited(subclass) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/haveapi/action.rb', line 42

def delayed_inherited(subclass)
  resource = Kernel.const_get(subclass.to_s.deconstantize)

  inherit_attrs(subclass)
  inherit_attrs_from_resource(subclass, resource, [:auth])

  i = @input.clone
  i.action = subclass

  o = @output.clone
  o.action = subclass

  m = {}

  @meta.each do |k,v|
    m[k] = v && v.clone
    next unless v
    m[k].action = subclass
  end

  subclass.instance_variable_set(:@input, i)
  subclass.instance_variable_set(:@output, o)
  subclass.instance_variable_set(:@meta, m)

  begin
    subclass.instance_variable_set(:@resource, resource)
    subclass.instance_variable_set(:@model, resource.model)
  rescue NoMethodError
    return
  end
end

.describe(context) ⇒ Object



174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
# File 'lib/haveapi/action.rb', line 174

def describe(context)
  authorization = (@authorization && @authorization.clone) || Authorization.new

  return false if (context.endpoint || context.current_user) && !authorization.authorized?(context.current_user)

  route_method = context.action.http_method.to_s.upcase
  context.authorization = authorization

  if context.endpoint
    context.action_instance = context.action.from_context(context)

    ret = catch(:return) do
      context.action_prepare = context.action_instance.prepare
    end

    return false if ret == false
  end

  {
      auth: @auth,
      description: @desc,
      aliases: @aliases,
      input: @input ? @input.describe(context) : {parameters: {}},
      output: @output ? @output.describe(context) : {parameters: {}},
      meta: @meta ? @meta.merge(@meta) { |_, v| v && v.describe(context) } : nil,
      examples: @examples ? @examples.map { |e| e.describe } : [],
      url: context.resolved_url,
      method: route_method,
      help: "#{context.url}?method=#{route_method}"
  }
end

.example(title = '', &block) ⇒ Object



157
158
159
160
161
162
# File 'lib/haveapi/action.rb', line 157

def example(title = '', &block)
  @examples ||= []
  e = Example.new(title)
  e.instance_eval(&block)
  @examples << e
end

.from_context(c) ⇒ Object



220
221
222
223
224
225
226
227
228
229
# File 'lib/haveapi/action.rb', line 220

def from_context(c)
  ret = new(nil, c.version, c.params, nil, c)
  ret.instance_exec do
    @safe_params = @params.dup
    @authorization = c.authorization
    @current_user = c.current_user
  end

  ret
end

.inherit_attrs_from_resource(action, r, attrs) ⇒ Object

Inherit attributes from resource action is defined in.



207
208
209
210
211
212
213
214
215
216
217
218
# File 'lib/haveapi/action.rb', line 207

def inherit_attrs_from_resource(action, r, attrs)
  begin
    return unless r.obj_type == :resource

  rescue NoMethodError
    return
  end

  attrs.each do |attr|
    action.method(attr).call(r.method(attr).call)
  end
end

.inherited(subclass) ⇒ Object



31
32
33
34
35
36
37
38
39
40
# File 'lib/haveapi/action.rb', line 31

def inherited(subclass)
  # puts "Action.inherited called #{subclass} from #{to_s}"

  subclass.instance_variable_set(:@obj_type, obj_type)

  if subclass.name
    # not an anonymouse class
    delayed_inherited(subclass)
  end
end

.initializeObject



74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
# File 'lib/haveapi/action.rb', line 74

def initialize
  return if @initialized

  check_build("#{self}.input") do
    input.exec
    model_adapter(input.layout).load_validators(model, input) if model
  end

  check_build("#{self}.output") do
    output.exec
  end

  model_adapter(input.layout).used_by(:input, self)
  model_adapter(output.layout).used_by(:output, self)

  if @meta
    @meta.each_value do |m|
      next unless m

      check_build("#{self}.meta.input") do
        m.input && m.input.exec
      end

      check_build("#{self}.meta.output") do
        m.output && m.output.exec
      end
    end
  end

  @initialized = true
end

.input(layout = nil, namespace: nil, &block) ⇒ Object



120
121
122
123
124
125
126
127
128
129
# File 'lib/haveapi/action.rb', line 120

def input(layout = nil, namespace: nil, &block)
  if block
    @input ||= Params.new(:input, self)
    @input.layout = layout
    @input.namespace = namespace
    @input.add_block(block)
  else
    @input
  end
end

.meta(type = :object, &block) ⇒ Object



142
143
144
145
146
147
148
149
150
151
# File 'lib/haveapi/action.rb', line 142

def meta(type = :object, &block)
  if block
    @meta ||= {object: nil, global: nil}
    @meta[type] ||= ::.new
    @meta[type].action = self
    @meta[type].instance_exec(&block)
  else
    @meta[type]
  end
end

.model_adapter(layout) ⇒ Object



116
117
118
# File 'lib/haveapi/action.rb', line 116

def model_adapter(layout)
  ModelAdapter.for(layout, resource.model)
end

.output(layout = nil, namespace: nil, &block) ⇒ Object



131
132
133
134
135
136
137
138
139
140
# File 'lib/haveapi/action.rb', line 131

def output(layout = nil, namespace: nil, &block)
  if block
    @output ||= Params.new(:output, self)
    @output.layout = layout
    @output.namespace = namespace
    @output.add_block(block)
  else
    @output
  end
end

.validate_buildObject



106
107
108
109
110
111
112
113
114
# File 'lib/haveapi/action.rb', line 106

def validate_build
  check_build("#{self}.input") do
    input.validate_build
  end

  check_build("#{self}.output") do
    output.validate_build
  end
end

Instance Method Details

#authorized?(user) ⇒ Boolean

Returns:



261
262
263
264
# File 'lib/haveapi/action.rb', line 261

def authorized?(user)
  @current_user = user
  @authorization.authorized?(user)
end

#current_userObject



266
267
268
# File 'lib/haveapi/action.rb', line 266

def current_user
  @current_user
end

#execObject

This method must be reimplemented in every action. It must not be invoked directly, only via safe_exec, which restricts output.



307
308
309
# File 'lib/haveapi/action.rb', line 307

def exec
  ['not implemented']
end

#inputObject



274
275
276
# File 'lib/haveapi/action.rb', line 274

def input
  @safe_params[ self.class.input.namespace ] if self.class.input
end

#metaObject



282
283
284
# File 'lib/haveapi/action.rb', line 282

def meta
  
end

#paramsObject



270
271
272
# File 'lib/haveapi/action.rb', line 270

def params
  @safe_params
end

#pre_execObject



301
302
303
# File 'lib/haveapi/action.rb', line 301

def pre_exec

end

#prepareObject

FIXME: is this correct behaviour? ++



297
298
299
# File 'lib/haveapi/action.rb', line 297

def prepare

end

#requestObject



278
279
280
# File 'lib/haveapi/action.rb', line 278

def request
  @request
end

#safe_execObject

Calls exec while catching all exceptions and restricting output only to what user can see. Return array [status, data|error, errors]



314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
# File 'lib/haveapi/action.rb', line 314

def safe_exec
  ret = catch(:return) do
    begin
      validate!
      prepare
      pre_exec
      exec
    rescue Exception => e
      tmp = call_class_hooks_as_for(Action, :exec_exception, args: [self, e])

      if tmp.empty?
        p e.message
        puts e.backtrace
        error('Server error occurred')
      end

      error(tmp[:message]) unless tmp[:status]
    end
  end

  safe_output(ret)
end

#safe_output(ret) ⇒ Object



341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
# File 'lib/haveapi/action.rb', line 341

def safe_output(ret)
  if ret
    output = self.class.output

    if output
      safe_ret = nil
      adapter = self.class.model_adapter(output.layout)
      out_params = self.class.output.params

      case output.layout
        when :object
          out = adapter.output(@context, ret)
          safe_ret = @authorization.filter_output(
              out_params,
              out,
              true
          )
          @reply_meta[:global].update(out.meta)

        when :object_list
          safe_ret = []

          ret.each do |obj|
            out = adapter.output(@context, obj)

            safe_ret << @authorization.filter_output(
                out_params,
                out,
                true
            )
            safe_ret.last.update({.namespace => out.meta}) unless meta[:no]
          end

        when :hash
          safe_ret = @authorization.filter_output(
              out_params,
              adapter.output(@context, ret),
              true
          )

        when :hash_list
          safe_ret = ret
          safe_ret.map! do |hash|
            @authorization.filter_output(
                out_params,
                adapter.output(@context, hash),
                true
            )
          end

        else
          safe_ret = ret
      end

      ns = {output.namespace => safe_ret}
      ns[.namespace] = @reply_meta[:global] unless meta[:no]

      [true, ns]

    else
      [true, {}]
    end

  else
    [false, @message, @errors]
  end
end

#set_meta(hash) ⇒ Object



286
287
288
# File 'lib/haveapi/action.rb', line 286

def set_meta(hash)
  @reply_meta[:global].update(hash)
end

#v?(v) ⇒ Boolean

Returns:



337
338
339
# File 'lib/haveapi/action.rb', line 337

def v?(v)
  @version == v
end

#validate!Object



253
254
255
256
257
258
259
# File 'lib/haveapi/action.rb', line 253

def validate!
  begin
    @params = validate
  rescue ValidationError => e
    error(e.message, e.to_hash)
  end
end