diff --git a/lib/data_mapper/resource.rb b/lib/data_mapper/resource.rb index 2210e93..d5100dd 100644 --- a/lib/data_mapper/resource.rb +++ b/lib/data_mapper/resource.rb @@ -387,6 +387,10 @@ module DataMapper resource end + def find_or_create(search_attributes, create_attributes = {}) + first(search_attributes) || create(search_attributes.merge(create_attributes)) + end + # TODO SPEC def copy(source, destination, options = {}) repository(destination) do diff --git a/spec/unit/resource_spec.rb b/spec/unit/resource_spec.rb index 01831ed..1391674 100644 --- a/spec/unit/resource_spec.rb +++ b/spec/unit/resource_spec.rb @@ -286,6 +286,13 @@ describe "DataMapper::Resource" do Planet.should respond_to(:first) Planet.should respond_to(:all) Planet.should respond_to(:[]) + Planet.should respond_to(:find_or_create) + end + + it 'should create if it cannot find (using find_or_create)' do + Planet.should_receive(:first).with({ :age => 1 }).and_return(nil) + Planet.should_receive(:create).with({ :age => 1, :name => "Fuzzy" }).and_return(true) + Planet.find_or_create({:age => 1}, { :name => "Fuzzy" }) end it '.exists? should return whether or not the repository exists' do