Module: FunWith::Patterns::GetAndSet
- Extended by:
- GetAndSetAPI
- Defined in:
- lib/fun_with/patterns/get_and_set.rb
Instance Method Summary collapse
- #get_and_set(*method_names) ⇒ Object
-
#get_and_set_block(name, *args, &block) ⇒ Object
the name() method can be called with a block (to change the block that is to be executed) or called with args to get the results of the block.
-
#get_and_set_boolean(*method_names) ⇒ Object
Would also like to do a boolean version which creates .bool? .bool! and .not_bool!.
Methods included from GetAndSetAPI
Instance Method Details
#get_and_set(*method_names) ⇒ Object
4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
# File 'lib/fun_with/patterns/get_and_set.rb', line 4 def get_and_set( *method_names ) for name in method_names if self.is_a?(Class) || self.is_a?(Module) eval "define_method( :#{name} ) do |*args| self.instance_variable_set( :@#{name}, args.first ) if args.length == 1 self.instance_variable_get( :@#{name} ) end" else m = Module.new m.get_and_set( *method_names ) self.extend( m ) end end end |
#get_and_set_block(name, *args, &block) ⇒ Object
the name() method can be called with a block (to change the block that is to be executed) or called with args to get the results of the block. Uses the internal object variable @name
50 51 52 53 54 55 56 57 58 59 60 61 |
# File 'lib/fun_with/patterns/get_and_set.rb', line 50 def get_and_set_block( name, *args, &block ) eval "define_method( :#{name} ) do |*args, &block| if block.is_a?( Proc ) # oddly, block_given? always returns false when defined this way raise ArgumentError.new( 'Call #{name}() with either a block or args' ) unless args.length == 0 self.instance_variable_set( :@#{name}, block ) block else block = self.instance_variable_get( :@#{name} ) ( block || Proc.new{} ).call( *args ) end end " end |
#get_and_set_boolean(*method_names) ⇒ Object
Would also like to do a boolean version which creates .bool? .bool! and .not_bool!
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
# File 'lib/fun_with/patterns/get_and_set.rb', line 21 def get_and_set_boolean( *method_names ) for name in method_names if self.is_a?(Class) || self.is_a?(Module) eval "define_method( :#{name}? ) do self.instance_variable_get( :@#{name} ) || false end define_method( :not_#{name}? ) do ! self.#{name}? end define_method( :#{name}! ) do self.instance_variable_set( :@#{name}, true ) end define_method( :not_#{name}! ) do self.instance_variable_set( :@#{name}, false ) end " else m = Module.new m.get_and_set_bool( *method_names ) self.extend( m ) end end end |