Permalink
Browse files

fix spec

add README for usage
  • Loading branch information...
1 parent 33a75c9 commit 52e4e6804ba9617c96fc3b7963bf6ede2025c4d8 @siuying siuying committed May 10, 2012
Showing with 78 additions and 7 deletions.
  1. +2 −1 .gitignore
  2. +25 −0 README.md
  3. +16 −6 lib/ns_notification_center.rb
  4. +35 −0 spec/ns_notification_center_spec.rb
View
@@ -1 +1,2 @@
-build/
+.rake_tasks~
+build/
View
@@ -98,6 +98,7 @@ Helper methods added to the class repsonsible for user preferences.
Helper methods added to give `NSIndexPath` a bit more or a Ruby
interface.
+
## Gestures
Extra methods on `UIView` for working with gesture recognizers. A gesture recognizer can be added using a normal Ruby block, like so:
@@ -123,3 +124,27 @@ button.when(UIControlEventTouchUpInside) do
self.view.backgroundColor = UIColor.redColor
end
```
+
+## NSNotificationCenter
+
+Helper methods to give NSNotificationCenter a Ruby-like interface:
+
+```ruby
+def viewWillAppear(animated)
+ notification_center.observe self, UIApplicationWillEnterForegroundNotification do
+ loadAndRefresh
+ end
+
+ notification_center.observe self, ReloadNotification do
+ loadAndRefresh
+ end
+end
+
+def viewWillDisappear(animated)
+ notification_center.unobserve self
+end
+
+def reload
+ notification_center.post ReloadNotification
+end
+```
@@ -1,12 +1,22 @@
class NSNotificationCenter
- def observe(key, name, object=nil, &proc)
- @observers = {} unless @observers
- @observers[key] = proc
+ attr_reader :observers
+
+ def observe(observer, name, object=nil, &proc)
+ @observers ||= {}
+ @observers[observer] ||= []
+ @observers[observer] << proc
self.addObserver(proc, selector:'call', name:name, object:object)
end
- def unobserve(key)
- proc = @observers[key].delete
- self.removeObserver(proc)
+ def unobserve(observer)
+ return unless @observers[observer]
+ @observers[observer].each do |proc|
+ removeObserver(proc)
+ end
+ @observers.delete(observer)
+ end
+
+ def post(name, object=nil, info=nil)
+ self.postNotificationName(name, object: object, userInfo:info)
end
end
@@ -0,0 +1,35 @@
+describe "NSNotificationCenter" do
+ SampleNotification = "SampleNotification"
+ after do
+ @observer = Object.new
+ end
+
+ after do
+ notification_center.unobserve(@observe)
+ end
+
+ it "return notification center" do
+ notification_center.should.not.be.nil
+ end
+
+ it "add observer" do
+ notified = false
+ notification_center.observe(@observe, SampleNotification) do
+ notified = true
+ end
+
+ lambda {
+ notification_center.post SampleNotification
+ }.should.change { notified }
+ end
+
+ it "remove observer" do
+ notification_center.observe(@observe, SampleNotification) do
+ notified = true
+ end
+
+ lambda {
+ notification_center.unobserve(@observe)
+ }.should.change { notification_center.observers.keys.size }
+ end
+end

0 comments on commit 52e4e68

Please sign in to comment.