Skip to content

Instantly share code, notes, and snippets.

@srpouyet
Created February 14, 2015 18:43
Show Gist options
  • Save srpouyet/0edac269ef990e5fd80b to your computer and use it in GitHub Desktop.
Save srpouyet/0edac269ef990e5fd80b to your computer and use it in GitHub Desktop.
Simple Wisper example
require 'wisper'
class User
include Wisper::Publisher
attr_accessor :name, :last_email_sent_at
def initialize(name, email)
@name, @email = name, email
end
def create
# Do stuff to create the user
broadcast(:user_created, self)
end
def destroy
# Do stuff to destroy the user
broadcast(:user_destroyed, self)
end
def rename(string)
self.name = string
broadcast(:user_renamed, self)
end
end
class EmailListener
def user_created(user)
# Do stuff that sends a welcome email
user.last_email_sent_at = Time.now
puts "Welcome email was sent to #{user.email}"
end
def user_destroyed(user)
# Do stuff that sends a farewell email
user.last_email_sent_at = Time.now
puts "Farewell email was sent to #{user.email}"
end
end
john = User.new('John', 'john@appleseed.com')
# => #<User:0x007fb1afc3ccc0 @email="john@appleseed.com", @name="John">
john.subscribe(EmailListener.new)
# => #<User:0x007fb1afc3ccc0
# @email="john@appleseed.com",
# @local_registrations=
# #<Set: {#<Wisper::ObjectRegistration:0x007fb1b0818f30
# @allowed_classes=#<Set: {}>,
# @broadcaster=#<Wisper::Broadcasters::SendBroadcaster:0x007fb1af067710>,
# @listener=#<EmailListener:0x007fb1b0818fd0>,
# @on=["all"],
# @prefix="",
# @with=nil>}>,
# @name="John">
john.last_email_sent_at
# => nil
john.create
# Welcome email was sent to john@appleseed.com
# => #<Set: {#<Wisper::ObjectRegistration:0x007fb1b0818f30
john.last_email_sent_at
# => 2015-02-14 19:39:48 +0100
john.destroy
# Farewell email was sent to john@appleseed.com
# => #<Set: {#<Wisper::ObjectRegistration:0x007fb1b0818f30
john.last_email_sent_at
# => 2015-02-14 19:40:20 +0100
john.rename('Richard')
# => #<Set: {#<Wisper::ObjectRegistration:0x007fb1b0818f30
john.name
# => "Richard"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment