Class: SyntaxSugar::NullObject
- Inherits:
- BasicObject
- Defined in:
- lib/syntax_sugar/null_object.rb
Constant Summary collapse
- VALID_TARGET_METHOD_TYPES =
[::String, ::Symbol]
- VALID_METHOD_MATCHERS_TYPES =
[::Regexp]
Instance Method Summary collapse
-
#initialize(subject_object, regexp_pointers = {}) ⇒ NullObject
constructor
A new instance of NullObject.
- #method_missing(method_name, *args, &block) ⇒ Object
Constructor Details
#initialize(subject_object, regexp_pointers = {}) ⇒ NullObject
Returns a new instance of NullObject.
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
# File 'lib/syntax_sugar/null_object.rb', line 6 def initialize(subject_object, regexp_pointers = {}) @__object__ = subject_object unless regexp_pointers.is_a?(::Hash) ::Kernel.raise(::ArgumentError, 'method pointer collection should be instance of Hash or Array') end if regexp_pointers.find{|k,v| !VALID_METHOD_MATCHERS_TYPES.any?{|klass| k.is_a?(klass) } } ::Kernel.raise(::ArgumentError,'invalid pointer given in the method definitions, use regular expression') end if regexp_pointers.find{|k,v| !VALID_TARGET_METHOD_TYPES.any?{|klass| v.is_a?(klass) } } ::Kernel.raise(::ArgumentError,'invalid target method given in the method definitions, use string or symbol') end @regexp_pointers = regexp_pointers end |
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(method_name, *args, &block) ⇒ Object
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
# File 'lib/syntax_sugar/null_object.rb', line 26 def method_missing(method_name, *args, &block) @regexp_pointers.each do |regexp, target_method| if method_name.to_s =~ regexp if regexp.source =~ /\(.*\)/ method_extraction = method_name.to_s.scan(regexp)[0][0] args.unshift(method_extraction) end return @__object__.__send__( target_method, *args, &block ) end end ::Kernel.raise(::NameError,"undefined local variable or method `#{method_name}' for #{@__object__.inspect}:SyntaxSugar::NullObject") end |