Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/TPei/observable
Implementation of the Observer pattern in crystal
https://github.com/TPei/observable
crystal design-pattern observable observer observer-pattern shard
Last synced: 25 days ago
JSON representation
Implementation of the Observer pattern in crystal
- Host: GitHub
- URL: https://github.com/TPei/observable
- Owner: TPei
- License: mit
- Created: 2016-06-10T14:45:50.000Z (over 8 years ago)
- Default Branch: master
- Last Pushed: 2023-04-10T13:22:37.000Z (over 1 year ago)
- Last Synced: 2024-08-04T01:07:06.429Z (4 months ago)
- Topics: crystal, design-pattern, observable, observer, observer-pattern, shard
- Language: Crystal
- Size: 18.6 KB
- Stars: 9
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
- awesome-crystal - observable - Implementation of the observer pattern (Misc)
README
# observable
###### This project is being built weekly with the latest crystal version (works with v1.7.2 🎉)
Simple implementation of the Observer pattern in Crystal. It is loosely based on the [Observable](http://ruby-doc.org/stdlib-2.0.0/libdoc/observer/rdoc/Observable.html) module from Ruby :)
The observer pattern is used to avoid tightly coupling objects that
stand in a one-to-many relationship.
It allows you to notify dependents about changes that happened to your
object, without having hard-coded dependencies :)## Installation
Add to your shard.yml
```yaml
dependencies:
observable:
github: tpei/observable
branch: master
```and then install the library into your project with
```bash
$ crystal deps
```## Usage
Include observable in the class you want to observe:
```crystal
require "observable/observable"class ToObserve
include Observable
end
```
This provides you with the following methods:
- `add_observer(observer : Observer)`
- `changed(state=true)`
- `changed?`
- `count_observers`
- `delete_observer(observer : Observer)`
- `delete_observers`
- `notify_observers`and as an added bonus, because I dislike the forced `changed` call precondition:
- `notify_observers!`, which notifies no matter if changed or notThen you can include observer in the class you want observing:
```crystal
require "observable/observer"class Observing
include Observerdef update(observable : Observable)
# do whatever you want to do if your observable changes
end
end
```
This only gives you an `update(observable : Observable)` method you should override, because it willl raise an error otherwise.Unfortunately we don't have ruby's verbosity and dynamism here so it's all a little more static. Especially the `update` method can really only pass on the `observable` object.