Class: Cogy::CogyController

Inherits:
ApplicationController show all
Defined in:
app/controllers/cogy/cogy_controller.rb

Overview

This is the entry point to the host application.

All Cogy-command invocations of the users end up being served by this controller (#command).

Instance Method Summary collapse

Instance Method Details

#commandObject

POST /<mount_path>/cmd/:cmd

Executes the requested Cogy::Command and returns the result.



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'app/controllers/cogy/cogy_controller.rb', line 12

def command
  cmd = params[:cmd]
  args = params.select { |k, _| k.start_with?("COG_ARGV_") }.to_unsafe_h
               .sort_by { |k, _| k.match(/\d+\z/)[0] }.to_h.values
  opts = params.select { |k, _| k.start_with?("COG_OPT_") }
               .transform_keys { |k| k.sub("COG_OPT_", "").downcase }
  user = params["COG_CHAT_HANDLE"]
  cog_env = request.request_parameters

  begin
    if (command = Cogy.commands[cmd])
      context = Context.new(command, args, opts, user, cog_env)

      result = if command.readonly
                 ActiveRecord::Base.connected_to(role: Cogy.readonly_role) do
                   context.invoke
                 end
               else
                 context.invoke
               end

      if result.is_a?(Hash)
        result = "COG_TEMPLATE: #{command.template || command.name}\n" \
                 "JSON\n" \
                 "#{result.to_json}"
      end
      render plain: result
    else
      render status: 404, plain: "The command '#{cmd}' does not exist."
    end
  rescue ActiveRecord::ReadOnlyError
    render status: 500, plain: "ActiveRecord::ReadOnlyError: " \
                               "Write SQL query attempted while in readonly mode.\n" \
                               "Please define the '#{cmd}' command using the " \
                               "`readonly: false` option.\n"
  rescue => e
    @user = user
    @cmd = cmd
    @exception = e
    respond_to do |format|
      format.any do
        render "/cogy/error", formats: :text, content_type: "text/plain", status: 500
      end
    end
  end
end

#inventoryObject

GET /<mount_path>/inventory

Returns the bundle config in YAML format, which is installable by Cog. It is typically hit by cogy:install (https://github.com/skroutz/cogy-bundle).



63
64
65
# File 'app/controllers/cogy/cogy_controller.rb', line 63

def inventory
  render body: Cogy.bundle_config.to_yaml, content_type: "application/x-yaml"
end