Browse files

Refactors to add backend registration (probably YAGNI, but was a fun …

…and useful exercise)
  • Loading branch information...
1 parent b90c4ef commit 1a8caf7f8c0ce63fc8914420d0b9723ce78c5c66 @alindeman alindeman committed Mar 5, 2012
View
22 lib/zonebie.rb
@@ -1,25 +1,33 @@
require "zonebie/version"
-require "zonebie/backends"
module Zonebie
class << self
def backend
- @backend ||= Zonebie::Backends::ActiveSupport.new
+ unless @backend
+ self.backend = :activesupport
+ end
+
@backend.name
end
- def backend=(backend)
- case backend
- when :activesupport
- @backend = Zonebie::Backends::ActiveSupport.new
+ def backend=(backend_name)
+ if backend = @backends.detect { |b| b.name == backend_name }
+ @backend = backend
else
- raise ArgumentError, "Unsupported backend"
+ raise ArgumentError, "Unsupported backend: #{backend_name}"
end
end
+ def add_backend(backend)
+ @backends ||= []
+ @backends << backend
+ end
+
def set_random_timezone
zones = @backend.zones
@backend.zone = zones[rand(zones.length)]
end
end
end
+
+require "zonebie/backends"
View
20 lib/zonebie/backends/active_support.rb
@@ -3,16 +3,20 @@
module Zonebie
module Backends
class ActiveSupport
- def name
- :activesupport
- end
+ Zonebie.add_backend(self)
- def zones
- ::ActiveSupport::TimeZone.all.map(&:name)
- end
+ class << self
+ def name
+ :activesupport
+ end
+
+ def zones
+ ::ActiveSupport::TimeZone.all.map(&:name)
+ end
- def zone=(zone)
- ::Time.zone = zone
+ def zone=(zone)
+ ::Time.zone = zone
+ end
end
end
end
View
8 spec/lib/zonebie/backends/active_support_spec.rb
@@ -2,7 +2,9 @@
describe Zonebie::Backends::ActiveSupport do
describe "#name" do
- its(:name) { should == :activesupport }
+ it "is :activesupport" do
+ described_class.name.should == :activesupport
+ end
end
describe "#zones" do
@@ -13,15 +15,15 @@
stub(:name => "Central Time (US & Canada)")
])
- subject.zones.should =~ ["Eastern Time (US & Canada)", "Central Time (US & Canada)"]
+ described_class.zones.should =~ ["Eastern Time (US & Canada)", "Central Time (US & Canada)"]
end
end
describe "#zone=" do
it "sets Time.zone provided by ActiveSupport" do
::Time.expects(:zone=).with("Eastern Time (US & Canada)")
- subject.zone = "Eastern Time (US & Canada)"
+ described_class.zone = "Eastern Time (US & Canada)"
end
end
end
View
11 spec/lib/zonebie_spec.rb
@@ -16,4 +16,15 @@
}.to raise_error(ArgumentError)
end
end
+
+ describe "#add_backend" do
+ it "allows registration of backends classes" do
+ expect {
+ Zonebie.backend = :my_new_backend
+ }.to raise_error(ArgumentError)
+
+ Zonebie.add_backend(stub(:name => :my_new_backend))
+ Zonebie.backend = :my_new_backend
+ end
+ end
end

0 comments on commit 1a8caf7

Please sign in to comment.