Class: ObservableDelegate
- Inherits:
-
Object
- Object
- ObservableDelegate
- Includes:
- Observable
- Defined in:
- lib/observable-delegate/version.rb,
lib/observable-delegate/observable_delegate.rb
Constant Summary collapse
- VERSION =
'0.0.1'
Instance Method Summary collapse
-
#initialize(subject, notify_with: nil, observe: [], delegate: []) ⇒ ObservableDelegate
constructor
A new instance of ObservableDelegate.
- #method_missing(method, *args, &block) ⇒ Object
-
#should_delegate?(method) ⇒ Boolean
should delegate if the subject has the method and the method is explicitly provided or there are not methods explicitly provided.
-
#should_notify?(method) ⇒ Boolean
should notify if the method is explicitly provied or no methods are explicitly provided.
Constructor Details
#initialize(subject, notify_with: nil, observe: [], delegate: []) ⇒ ObservableDelegate
Returns a new instance of ObservableDelegate.
6 7 8 9 10 11 |
# File 'lib/observable-delegate/observable_delegate.rb', line 6 def initialize(subject, notify_with: nil, observe: [], delegate: []) @subject = subject @notify_with = notify_with @observe_methods = observe @delegate_methods = delegate end |
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(method, *args, &block) ⇒ Object
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
# File 'lib/observable-delegate/observable_delegate.rb', line 13 def method_missing(method, *args, &block) if should_delegate?(method) && should_notify?(method) result = @subject.send(method, *args, &block) changed payload = if @notify_with @subject.send(@notify_with) else result end notify_observers(payload) result elsif should_delegate?(method) @subject.send(method, *args, &block) else # create a no method error here and remove the # last backtrace from it so that it points to # where this method was used. begin raise NoMethodError.new("No method #{method} found for #{@subject.class}") rescue NoMethodError => e e.set_backtrace(e.backtrace[1..-1]) raise e end end end |
Instance Method Details
#should_delegate?(method) ⇒ Boolean
should delegate if the subject has the method and the method is explicitly provided or there are not methods explicitly provided
46 47 48 49 50 |
# File 'lib/observable-delegate/observable_delegate.rb', line 46 def should_delegate?(method) @subject.methods.include?(method) && (@delegate_methods.include?(method) || @delegate_methods.empty?) end |
#should_notify?(method) ⇒ Boolean
should notify if the method is explicitly provied or no methods are explicitly provided
54 55 56 |
# File 'lib/observable-delegate/observable_delegate.rb', line 54 def should_notify?(method) @observe_methods.include?(method) || @observe_methods.empty? end |