Class: Apiculture::Action

Inherits:
Object
  • Object
show all
Defined in:
lib/apiculture/action.rb

Overview

An Action is like a Sinatra route method wrapped in a class. It gets instantiated with a number of instance variables (via keyword arguments) and the Sinatra application calling the action.

All the methods available within Sinatra are also available within the Action, via method delegation (this primarily concerns methods like request, env, params and so forth).

The main work method is perform which should return a data structure that can be converted into JSON by the caller.

Instance Method Summary collapse

Constructor Details

#initialize(sinatra_app, **ivars) ⇒ Action

Initialize a new BasicAction, with the given Sintra application and a hash of keyword arguments that will be converted into instance variables.



14
15
16
17
# File 'lib/apiculture/action.rb', line 14

def initialize(sinatra_app, **ivars)
  ivars.each_pair {|k,v| instance_variable_set("@#{k}", v) }
  @_sinatra_app = sinatra_app
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(m, *a, &b) ⇒ Object

Respond to all the methods the contained Sinatra app supports



30
31
32
33
34
35
36
# File 'lib/apiculture/action.rb', line 30

def method_missing(m, *a, &b)
  if @_sinatra_app.respond_to?(m)
    @_sinatra_app.public_send(m, *a, &b)
  else
    super
  end
end

Instance Method Details

#bail(with_error_message, status: 400, **attrs_for_json_response) ⇒ Object

Halt with a JSON error message (delegates to Sinatra’s halt() under the hood)



20
21
22
# File 'lib/apiculture/action.rb', line 20

def bail(with_error_message, status: 400, **attrs_for_json_response)
  @_sinatra_app.json_halt(with_error_message, status: status, **attrs_for_json_response)
end

#performObject

Performs the action and returns it’s result.

If the action result is an Array or a Hash, it will be converted into JSON and output.

If something else is returned an error will be raised.



44
45
# File 'lib/apiculture/action.rb', line 44

def perform
end

#respond_to_missing?(*a) ⇒ Boolean

Respond to all the methods the contained Sinatra app supports

Returns:

  • (Boolean)


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

def respond_to_missing?(*a)
  super || @_sinatra_app.respond_to?(*a)
end