Class: Console1984::Shield::MethodInvocationShell

Inherits:
Object
  • Object
show all
Includes:
Freezeable
Defined in:
lib/console1984/shield/method_invocation_shell.rb

Overview

Prevents invoking a configurable set of methods

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Freezeable

freeze_all, included

Constructor Details

#initialize(invocation) ⇒ MethodInvocationShell

Returns a new instance of MethodInvocationShell.



13
14
15
16
# File 'lib/console1984/shield/method_invocation_shell.rb', line 13

def initialize(invocation)
  @class_name, methods = invocation.to_a
  @methods = Array(methods)
end

Instance Attribute Details

#class_nameObject (readonly)

Returns the value of attribute class_name.



11
12
13
# File 'lib/console1984/shield/method_invocation_shell.rb', line 11

def class_name
  @class_name
end

#methodsObject (readonly)

Returns the value of attribute methods.



11
12
13
# File 'lib/console1984/shield/method_invocation_shell.rb', line 11

def methods
  @methods
end

#only_for_user_commandsObject (readonly)

Returns the value of attribute only_for_user_commands.



11
12
13
# File 'lib/console1984/shield/method_invocation_shell.rb', line 11

def only_for_user_commands
  @only_for_user_commands
end

Class Method Details

.install_for(invocations) ⇒ Object



6
7
8
# File 'lib/console1984/shield/method_invocation_shell.rb', line 6

def install_for(invocations)
  Array(invocations).each { |invocation| self.new(invocation).prevent_methods_invocation }
end

Instance Method Details

#build_protection_moduleObject



22
23
24
25
26
27
28
29
# File 'lib/console1984/shield/method_invocation_shell.rb', line 22

def build_protection_module
  source = protected_method_invocations_source
  Module.new do
    class_eval <<~RUBY, __FILE__, __LINE__ + 1
      #{source}
    RUBY
  end
end

#prevent_methods_invocationObject



18
19
20
# File 'lib/console1984/shield/method_invocation_shell.rb', line 18

def prevent_methods_invocation
  class_name.to_s.constantize.prepend build_protection_module
end

#protected_method_invocation_source_for(method) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
# File 'lib/console1984/shield/method_invocation_shell.rb', line 35

def protected_method_invocation_source_for(method)
  <<~RUBY
    def #{method}(*args)
      if Console1984.command_executor.from_irb?(caller)
        raise Console1984::Errors::ForbiddenCommandAttempted
      else
        super
      end
    end
  RUBY
end

#protected_method_invocations_sourceObject



31
32
33
# File 'lib/console1984/shield/method_invocation_shell.rb', line 31

def protected_method_invocations_source
  methods.collect { |method| protected_method_invocation_source_for(method) }.join("\n")
end