Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Allow 'find' calls from ActiveRecord [fixes #2].

  • Loading branch information...
commit 8011cb60bc6c07c91a485eb990be4b44f8e4a660 1 parent 5f0041c
@stephencelis stephencelis authored
Showing with 26 additions and 2 deletions.
  1. +8 −0 lib/acts_as_singleton.rb
  2. +18 −2 test/acts_as_singleton_test.rb
View
8 lib/acts_as_singleton.rb
@@ -46,6 +46,14 @@ def instance
def inspect
super.sub(/id: .+?, /) {} # Irrelevant.
end
+
+ def find(*args)
+ unless caller.first.include?("lib/active_record")
+ raise NoMethodError,
+ "private method `find' called for #{inspect}"
+ end
+ super # (:first) || create
+ end
end
def clone
View
20 test/acts_as_singleton_test.rb
@@ -1,5 +1,4 @@
require 'test/unit'
-require 'rubygems'
require 'active_record'
require "#{File.dirname(__FILE__)}/../init"
require 'active_support'
@@ -14,6 +13,10 @@ def setup_db
t.text :welcome_message
t.timestamp :published_at, :expired_at
end
+
+ create_table :cottages do |t|
+ t.belongs_to :home_away_from_home, :polymorphic => true
+ end
end
end
@@ -26,11 +29,17 @@ def teardown_db
setup_db
class HomepageSettings < ActiveRecord::Base
acts_as_singleton
+ has_many :cottages, :as => :home_away_from_home
end
class LoggedInSettings < HomepageSettings
end
+class Cottage < ActiveRecord::Base
+ belongs_to :home_away_from_home, :polymorphic => true
+ validates_associated :home_away_from_home
+end
+
class ActsAsSingletonTest < ActiveSupport::TestCase
setup do
setup_db
@@ -38,6 +47,10 @@ class ActsAsSingletonTest < ActiveSupport::TestCase
teardown do
teardown_db
+
+ HomepageSettings.instance_eval do
+ remove_instance_variable :@instance if defined? @instance
+ end
end
test "should be provocative" do
@@ -78,7 +91,6 @@ class ActsAsSingletonTest < ActiveSupport::TestCase
end
test "should honor STI" do
- ActiveRecord::Base.logger = STDOUT
ActiveRecord::Base.clear_active_connections!
HomepageSettings.instance # Fetch parent.
LoggedInSettings.instance # Fetch child.
@@ -86,4 +98,8 @@ class ActsAsSingletonTest < ActiveSupport::TestCase
LoggedInSettings.instance # Fetch again.
end
end
+
+ test "should honor polymorphism" do
+ HomepageSettings.instance.cottages.create
+ end
end
Please sign in to comment.
Something went wrong with that request. Please try again.