Method: Module#guard_method
- Defined in:
- lib/quality_extensions/module/guard_method.rb
#guard_method(guard_method_name, guard_variable) ⇒ Object
A guard method (by this definition anyway) is a method that sets a flag, executes a block, and then returns the flag to its previous value. It ensures that the flag is set during the execution of the block.
In the simplest case, you’d use it like this:
class A
guard_method :disable_stupid_stuff!, :@stupid_stuff_disabled
end
a = A.new
a.disable_stupid_stuff! do # Causes @stupid_stuff_disabled to be set to true
# Section of code during which you don't want any stupid stuff to happen
end # Causes @stupid_stuff_disabled to be set back to false
# Okay, a, you can resume doing stupid stuff again...
If you want your guard method to disable the flag rather than enable it, simply pass false to the guard method.
These calls can be nested however you wish:
a.guard_the_fruit! do
a.guard_the_fruit!(false) do
assert_equal false, a.guarding_the_fruit?
end
assert_equal true, a.guarding_the_fruit?
end
You can also use the guard methods as normal flag setter/clearer methods by simply not passing a block to it. Hence
a.guard_the_fruit!
will simply set @guarding_the_fruit to true, and
a.guard_the_fruit!(false)
will set @guarding_the_fruit to false.
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
# File 'lib/quality_extensions/module/guard_method.rb', line 53 def guard_method(guard_method_name, guard_variable) raise ArgumentError.new("Expected an instance variable name but got #{guard_variable}") if guard_variable !~ /^@([\w_]+)$/ guard_variable.to_s =~ /^@([\w_]+)$/ # Why didn't the regexp above set $1 ?? class_eval do bool_attr_accessor $1.to_sym end module_eval <<-End, __FILE__, __LINE__+1 def #{guard_method_name}(new_value = true, &block) old_guard_state, #{guard_variable} = #{guard_variable}, new_value if block_given? begin returning = yield ensure #{guard_variable} = old_guard_state returning end end end End end |