Module: InsaneHook

Defined in:
lib/insane_hook.rb,
lib/insane_hook/version.rb

Defined Under Namespace

Modules: ClassMethods Classes: CommandNotRunError, MissingArgumentError

Constant Summary collapse

ARGS_VAR =
:@@_command
REQUIRED_ARGS =
:required
OPTIONAL_ARGS =
:optional
RESULT_VAR =
:@_result
NO_ARG =
:_no_value
VERSION =
"0.3.0"

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(mod) ⇒ Object



12
13
14
15
16
17
18
# File 'lib/insane_hook.rb', line 12

def self.included(mod)
  mod.class_variable_set(::InsaneHook::ARGS_VAR, {REQUIRED_ARGS => [], OPTIONAL_ARGS => []})
  mod.extend(ClassMethods)
  mod.define_singleton_method(:need, mod.instance_method(:_need))
  mod.define_singleton_method(:allow, mod.instance_method(:_allow))
  mod.define_singleton_method(:call, mod.instance_method(:_call))
end

Instance Method Details

#_allow(key) ⇒ Object



39
40
41
42
43
44
# File 'lib/insane_hook.rb', line 39

def _allow(key)
  fail "#{key} is not a symbol" unless key.is_a? Symbol
  args = self.class_variable_get(::InsaneHook::ARGS_VAR)
  args[OPTIONAL_ARGS] << key
  self.class_variable_set(::InsaneHook::ARGS_VAR, args)
end

#_call(**args, &block) ⇒ Object



46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/insane_hook.rb', line 46

def _call(**args, &block)
  if block_given?
    raise "Block cannot take arguments" if block.arity > 0
    raise "call method already defined" if self.instance_methods.include?(:call)
    define_method(:call) do
      result(nil)
      instance_eval(&block)
      self
    end
  else
    new(**args).call
  end

end

#_need(key) ⇒ Object



32
33
34
35
36
37
# File 'lib/insane_hook.rb', line 32

def _need(key)
  fail "#{key} is not a symbol" unless key.is_a? Symbol
  args = self.class_variable_get(::InsaneHook::ARGS_VAR)
  args[REQUIRED_ARGS] << key
  self.class_variable_set(::InsaneHook::ARGS_VAR, args)
end

#result(value = NO_ARG) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
# File 'lib/insane_hook.rb', line 20

def result(value=NO_ARG)
  if value == NO_ARG
    if instance_variable_defined?(::InsaneHook::RESULT_VAR)
      instance_variable_get(::InsaneHook::RESULT_VAR)
    else
      raise CommandNotRunError
    end
  else
    instance_variable_set(::InsaneHook::RESULT_VAR, value)
  end
end