gitlab-org--gitlab-foss/lib/gitlab/quick_actions/command_definition.rb

87 lines
2.1 KiB
Ruby
Raw Normal View History

2016-08-12 21:17:18 -04:00
module Gitlab
module QuickActions
2016-08-12 21:17:18 -04:00
class CommandDefinition
attr_accessor :name, :aliases, :description, :explanation, :params,
:condition_block, :parse_params_block, :action_block
2016-08-12 21:17:18 -04:00
def initialize(name, attributes = {})
@name = name
@aliases = attributes[:aliases] || []
@description = attributes[:description] || ''
@explanation = attributes[:explanation] || ''
@params = attributes[:params] || []
2016-08-17 19:58:44 -04:00
@condition_block = attributes[:condition_block]
@parse_params_block = attributes[:parse_params_block]
@action_block = attributes[:action_block]
2016-08-12 21:17:18 -04:00
end
def all_names
[name, *aliases]
end
def noop?
action_block.nil?
end
def available?(context)
2016-08-12 21:17:18 -04:00
return true unless condition_block
context.instance_exec(&condition_block)
end
def explain(context, arg)
return unless available?(context)
if explanation.respond_to?(:call)
execute_block(explanation, context, arg)
else
explanation
end
end
def execute(context, arg)
return if noop? || !available?(context)
2016-08-12 21:17:18 -04:00
execute_block(action_block, context, arg)
2016-08-12 21:17:18 -04:00
end
def to_h(context)
2016-08-12 21:17:18 -04:00
desc = description
if desc.respond_to?(:call)
desc = context.instance_exec(&desc) rescue ''
end
2017-06-06 04:49:36 -04:00
prms = params
if prms.respond_to?(:call)
prms = Array(context.instance_exec(&prms)) rescue params
end
2016-08-12 21:17:18 -04:00
{
name: name,
aliases: aliases,
description: desc,
2017-06-06 04:49:36 -04:00
params: prms
2016-08-12 21:17:18 -04:00
}
end
private
def execute_block(block, context, arg)
if arg.present?
parsed = parse_params(arg, context)
context.instance_exec(parsed, &block)
elsif block.arity == 0
context.instance_exec(&block)
end
end
def parse_params(arg, context)
return arg unless parse_params_block
context.instance_exec(arg, &parse_params_block)
end
2016-08-12 21:17:18 -04:00
end
end
end