SVN and SVK
Dear Lazyweb:
I would like to take an existing SVN repository of a project (like say, Typo), check out a tagged version, create local modifications and save the modified version in a local/home SVN repository(my blog). Later, I'd like to sync up the local version to a new tagged version of the original repository (Typo), handle any merges locally and then check in the result into my local repository again. Rinse and repeat, ad infinitum.
Is SVK the right job for this? Has anybody done something like this? Essentially its the equivalent of creating a branch on a SVN repository but having that branch in an entirely separate SVN repository instance. I don't have experience with this, so I'd greatly appreciate any pointers anybody out there might have.
Patterns in Ruby: Observer Pattern
Another easy to implement pattern in Ruby is the Observer pattern. The Observer pattern is a publish/subscribe mechanism where an objects can register to be notified of state changes (or observe changes) on another observed object. This pattern may often become refactored into a more general event framework (where objects fire events off into queues to which there are listeners subscribed).
The basic implementation
Here's a look at a simple ruby implementation:
class Observable
def initialize
@listeners = []
end
def register_listener(listener)
@listeners << listener
end
def unregister_listener(listener)
@listeners.remove(listener)
end
def run
notify_listeners("Hello!")
end
protected
def notify_listeners(event)
@listeners.each {|l| l.notify(event) }
end
end
class Listener
def initialize(observable)
observable.register_listener(self)
end
def notify(event)
puts "Notified of '#{event}'"
end
end
observable = Observable.new
listener = Listener.new(observable)
observable.run #=> Notified of 'Hello!'The pattern itself in this form is pretty general. So general, in fact, that there is a module mixin of Observer inside the standard ruby library (observer.rb). There's some good documentation in there, and it provides a simpler path to this implementation:
require "observer"
class TV
include Observable
def initialize(channel)
@channel = channel
end
def up
@channel += 1
changed
notify_observers(@channel)
end
end
class ChannelWatcher
def initialize(tv)
tv.add_observer(self)
end
def update(channel)
puts "Changed channel to #{channel}"
end
end
tv = TV.new(160)
watcher = ChannelWatcher.new(tv)
tv.up #=> Changed channel to 161Please be aware that the API is a little different from my initial example.
Moving towards events
Both of the above implementations rely on a generic observer pattern, but the Observer pattern can often evolve into a simple event mechanism. The difference is that instead of firing a generic event object via a generic notify method, the move towards events uses unique method names, and filters events to notify only those interested in the type of event occurring.
Let's see a TV example where we move towards a more specialized event firing version of the pattern:
require "observer"
class TV
def initialize(channel)
@channel = channel
@listeners = []
end
def add_listener(listener)
@listeners << listener
end
def up
@channel += 1
@listeners.each {|l| l.channel_increased(@channel) }
end
def down
@channel -= 1
@listeners.each {|l| l.channel_decreased(@channel) }
end
end
class ChannelUpWatcher
def initialize(tv)
tv.add_listener(self)
end
def channel_increased(channel)
puts "Changed channel to #{channel}"
end
def channel_decreased
# do nothing...
end
end
tv = TV.new(160)
watcher = ChannelUpWatcher.new(tv)
tv.up #=> Changed channel to 161In this instance we can fire off events for surfing the Tv upwards or downwards (in channels) separately, though we still register listeners into a generic pool, and listeners are expected to contain both event methods. Variations of this can be done to register listeners into sub-groups upon registration by calling unique methods names for each registration, or by passing in a Filter object that can be used to filter to the events the listener cares about. In filtering at registration we can avoid listeners having to implement every event firing method and minimize the number of events fired off.
One illustration of this observer based event model is the Java Swing events API.
Extending the pattern towards this event firing mechanism even further we'd likely move into using queues and firing events off to the queues themselves rather than directly to observers. Observers would then become subscribers to the queues.
Using blocks and procs
The Observer pattern as described above is the typical pattern followed in most languages without closures, lambdas or functors. In Ruby we have the ability to throw around closures/blocks so we can take the pattern a little further.
Let's revisit our original implementation, but let's add the ability to register the callback function to be performed upon notification.
class Observable
def initialize
@listeners = []
end
def register_listener(&blk)
@listeners << blk
end
def unregister_listener(&blk)
@listeners.remove(blk)
end
def run
notify_listeners("Hello!")
end
protected
def notify_listeners(event)
@listeners.each {|l| l.call(event) }
end
end
class Listener
def initialize(observable)
observable.register_listener {|event| "Notified of '#{event}'"}
end
end
observable = Observable.new
listener = Listener.new(observable)
observable.run #=> Notified of 'Hello!'This is the model illustrated in the Tk bindings for Ruby - you can see examples of usage in Programming Ruby's section on binding events in Tk. That section and their section on blocks as closures begin to broach the how closures capture the context in which they were defined - allowing for some very interesting and complex behavior in using blocks and procs as event or observer callbacks (allowing you to refer to objects available at the scope of the block definition, not when the callback/block execution occurs).
Patterns in Ruby: Singleton Pattern
The Singleton pattern is the black sheep of the pattern family. It was easy to grasp, developers everywhere applied it liberally, and an inevitable backlash came against its overuse.
I won't make any judgments or reccomendations on when to use it - but I will show you just how easy it is to apply in Ruby.
The literal translation of the pattern is to create a class level instance method and to hide the new method.
class Example
def initialize
# do something?
end
def self.instance
return @@instance if defined? @@instance
@@instance = new
end
private_class_method :new
end
puts Example.instance.object_id #=> 21783380
puts Example.instance.object_id #=> 21783380This example gives you the basic idea, but it doesn't cover many cases you'd like to handle, like cloning or duping the singleton. It also doesn't hide the class level allocate method, which means a sneaky coder could still create another instance through some hacking.
Lastly, it's not thread safe.
Luckily, Ruby already provides a module for making classes singletons. It's in the standard library, inside 'singleton.rb'. Here's how you use it:
require 'singleton'
class Example
include Singleton
endThis module will do the same thing as my example above but will also handle hiding allocate, overriding the clone and dup methods, and is thread safe. The library file itself contains a bunch of examples of its usage, and those interested should definitely read through it.
One thing to note about these implementations is that the instance method takes no arguments, so none are passed on to the object's constructor. This makes sense because the first time instance is called those will be the arguments used for this global instance. Setters are typically more appropriate for most singletons.
Since singletons are global in nature setters should be at the class level. As an extra bonus here's the implementation of the class level attr_ methods to generate the vanilla getter/setter methods (stolen from Rails).
class Class # :nodoc:
def cattr_reader(*syms)
syms.flatten.each do |sym|
class_eval(<<-EOS, __FILE__, __LINE__)
unless defined? @@#{sym}
@@#{sym} = nil
end
def self.#{sym}
@@#{sym}
end
def #{sym}
@@#{sym}
end
EOS
end
end
def cattr_writer(*syms)
syms.flatten.each do |sym|
class_eval(<<-EOS, __FILE__, __LINE__)
unless defined? @@#{sym}
@@#{sym} = nil
end
def self.#{sym}=(obj)
@@#{sym} = obj
end
def #{sym}=(obj)
@@#{sym} = obj
end
EOS
end
end
def cattr_accessor(*syms)
cattr_reader(*syms)
cattr_writer(*syms)
end
endNow we can create a more realistic singleton:
require 'singleton'
class JimmyGrimble
include Singleton
cattr_reader :boots
cattr_accessor :football
endPatterns in Ruby: Decorator Pattern
I've been a fan of the work that was done by the Gang of Four on Design Patterns: Elements of Reusable Object-Oriented Software (Addison-Wesley Professional Computing Series), Martin Fowler's Refactoring: Improving the Design of Existing Code
and the bridge book by Joshua Kerievsky, Refactoring to Patterns
.
I haven't seen a lot of information out there on how Ruby changes the game: ways to apply these patterns using Ruby idioms, new patterns that show up, patterns that fall away. So I've decided that as I go along I'll try and document the new twists as I see them.
Today's article is the twist on the Decorator pattern. The Decorator pattern wraps the original object in a new one which will add functionality to some of the methods and then delegate to the original object. The prototypical example is decorating a window object.
A Decorator Example
public interface Window {
public void draw();
}In Java, we'd probably use a decorator to add scroll bars.
public Class VerticalScrollWindow implements Window {
private Window window;
public VerticalScrollWindow(Window window) {
this.window = window;
}
public void draw() {
drawScrollBar();
window.draw();
}
}The basic concept is that we'll usually want to be adding some behavior around a particular method call to extend behavior, while retaining the same interface.
Ruby
In ruby, we have a number of options to achieve this pattern. First, let's define our original Window in Ruby code:
class Window
def draw
# do some drawing here...
end
endTranslating the pattern literally
Given ruby's duck-typing nature, we could easily create a VerticalScrollWindow that wraps the original Window when we create the original window object, and pass that around. In fact we could patch only the single method and add a method_missing implementation that always delegated to the original Window.
class VerticalScrollWindow
def initialize(window)
@window = window
end
def draw
draw_vertical_scrollbar
window.draw
end
def method_missing(method, *args, &block)
@window.send(method, *args, &block)
end
endThis approach could be evolved to a much higher level using method_missing tricks and dynamic modifications. One could create a generic Proxy class which took a target class and intercepted all method calls, executing pre- and post- method blocks for specific methods. I'll leave that as an exercise for the reader for now...
Using Alias
Another option we have is to "monkeypatch" the original class (or specific instances of it). The idea here is to rename the old implementation of the method, insert a new implementation and have that refer to the renamed original.
class Window
def draw
# do some drawing here...
end
# some code...
alias :original_draw :draw
def draw
draw_vertical_scrollbar
original_draw
end
endBuilding pre and post hooks
Our last option is to build pre and post method hooks into the original class definition. Obviously, this approach requires the original class' author to explicitly build in callback hooks. This approach can be found in Capistrano (you can add tasks which get executed before or after well known tasks), or in ActiveRecord (lifecycle type callbacks - i.e. before_save, after_destroy).
This option is a bit more advanced and differs in the approach taken. To learn how Capistrano does it, dive into capistrano/actor.rb, line 118. Each task is defined as a method which explicitly calls before and after methods if they exist.
For ActiveRecord, please refer to activerecord/callback.rb. ActiveRecord goes a little further by allowing class level methods to add pre- and post- code blocks to be executed which will be inherited down the class hierarchy. They also allow instance level methods to be defined for each hook which would not be inherited.
Update: Francisco points us to a great article on Decorator showing some other possible Ruby implementations.