Module: StricterGlobalUsage::Strategy
- Defined in:
- lib/stricter_global_usage/strategy.rb
Overview
The Strategy module represents the action to take when a function is called and its argument defaults to the value of a global variable.
Consumers of StricterGlobalUsage usually will only need to use the use
method to specify which strategy should be applied when necessary.
There are three built-in strategies (although consumers are free to add more through the add
method):
-
raise
: The default strategy. Raises ::StricterGlobalUsage::DefaultGlobalVariableUsed exception. -
warn
: Logs the call with Kernel.warn, then continues to execute the original method. -
silent
: Does nothing, then continues to execute the original method.
Class Method Summary collapse
-
.add(name, &block) ⇒ Object
Create a new strategy.
-
.apply(method) ⇒ Object
Apply the current strategy (warns, raises an exception, or does something else the user chose).
-
.use(name) ⇒ Object
Use the strategy represented by the given name.
-
.with(name, &block) ⇒ Object
Use the strategy represented by the given name for the context of the given block, then restore the previous strategy.
Class Method Details
.add(name, &block) ⇒ Object
Create a new strategy. When that strategy is applied, it will be passed in information about the call to Strategy.apply.
::StricterGlobalUsage::Strategy.add(:my_log) do |method_name|
MyLogger.log("Used #{method_name} whose argument fell back to a global variable")
end
29 30 31 |
# File 'lib/stricter_global_usage/strategy.rb', line 29 def self.add(name, &block) @strategies[name] = block end |
.apply(method) ⇒ Object
Apply the current strategy (warns, raises an exception, or does something else the user chose). When you call apply yourself, you are expected to supply the name of the method as (e.g.) ‘Dog#bark’.
19 20 21 |
# File 'lib/stricter_global_usage/strategy.rb', line 19 def self.apply(method) @strategies[@name].call(method) end |
.use(name) ⇒ Object
Use the strategy represented by the given name.
::StricterGlobalUsage::Strategy.use(:my_log)
36 37 38 |
# File 'lib/stricter_global_usage/strategy.rb', line 36 def self.use(name) @name = name end |
.with(name, &block) ⇒ Object
Use the strategy represented by the given name for the context of the given block, then restore the previous strategy.
::StricterGlobalUsage::Strategy.with(:silent) do
::SomeVendorLibrary.do_stuff
end
46 47 48 49 50 51 52 53 54 |
# File 'lib/stricter_global_usage/strategy.rb', line 46 def self.with(name, &block) orig_name = @name begin use(name) yield ensure @name = orig_name end end |