• Stars
    star
    9
  • Rank 1,939,727 (Top 39 %)
  • Language
    Crystal
  • License
    MIT License
  • Created over 8 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Implementation of the Observer pattern in crystal

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 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

dependencies:
  observable:
    github: tpei/observable
    branch: master

and then install the library into your project with

$ crystal deps

Usage

Include observable in the class you want to observe:

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 not

Then you can include observer in the class you want observing:

require "observable/observer"

class Observing
  include Observer

  def 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.