Skip to content

Commit

Permalink
Use #create when a model doesn't know about #create!
Browse files Browse the repository at this point in the history
Sequel 3.0 (and maybe earlier versions?) doesn't define a #create!
method on models, only #create.
  • Loading branch information
foca committed May 18, 2009
1 parent 4785e5a commit 1d9eef7
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 6 deletions.
3 changes: 2 additions & 1 deletion lib/spawner.rb
Expand Up @@ -8,6 +8,7 @@ def spawner &default

def spawn attrs = {}
@@spawn[self.name].call(model = OpenStruct.new)
create!(model.send(:table).merge(attrs))
factory_method = respond_to?(:create!) ? :create! : :create
send(factory_method, model.send(:table).merge(attrs))
end
end
26 changes: 21 additions & 5 deletions test/all_test.rb
Expand Up @@ -2,14 +2,14 @@
require 'contest'
require File.dirname(__FILE__) + "/../lib/spawner"

class Foo
class Base
attr_accessor :attributes

def initialize(attrs = {})
@attributes = attrs
end

def self.create!(attrs = {})
def self.create(attrs = {})
new(attrs)
end

Expand All @@ -19,9 +19,15 @@ def self.name; "Foo" end

extend Spawner

spawner do |foo|
foo.bar = 7
foo.baz = 8
spawner do |object|
object.bar = 7
object.baz = 8
end
end

class Foo < Base
class << self
alias_method :create!, :create
end
end

Expand All @@ -34,6 +40,9 @@ def self.name; "Bar" end
end
end

class Baz < Base
end

class TestFoo < Test::Unit::TestCase
should "have a name class method" do
assert Foo.respond_to?(:name)
Expand Down Expand Up @@ -97,5 +106,12 @@ class TestFoo < Test::Unit::TestCase
end
end
end

context "and it doesn't understand #create! (only #create)" do
should "work anyway" do
baz = Baz.spawn :bar => 1
assert_equal 1, baz.bar
end
end
end
end

0 comments on commit 1d9eef7

Please sign in to comment.