Skip to content

Instantly share code, notes, and snippets.

@tal
Created June 21, 2012 20:03
Show Gist options
  • Select an option

  • Save tal/2968211 to your computer and use it in GitHub Desktop.

Select an option

Save tal/2968211 to your computer and use it in GitHub Desktop.
class Contact < Person
end
>> Person.find_or_create_by_external('email', '[email protected]') { |p, id| p.becomes Contact }
MOPED: localhost:27017 QUERY database=delight_development collection=people selector={"identifiers.key"=>"[email protected]", "identifiers._type"=>"UserIdentifier::Email"} flags=[:slave_ok] limit=-1 skip=0 fields=nil (0.0ms)
MOPED: localhost:27017 INSERT database=delight_development collection=people documents=[{"_id"=>4fe37df00420ba6116000006, "_type"=>"Contact", "updated_at"=>2012-06-21 20:02:56 UTC, "created_at"=>2012-06-21 20:02:56 UTC, "identifiers"=>[{"_id"=>4fe37df00420ba6116000007, "_type"=>"UserIdentifier::Email", "verified"=>false, "key"=>"[email protected]", "key_hash"=>"6dcf8f85513186d6f8cd8d3274f6eeaae22adb85"}]}] flags=[] (0.0ms)
=> #<Person _id: 4fe37df00420ba6116000006, _type: "Contact", created_at: 2012-06-21 20:02:56 UTC, updated_at: 2012-06-21 20:02:56 UTC, first_name: nil, last_name: nil>
class << Person
def find_or_initialize_by_external type, key
unless user = external(type,key).first
user = new
identifier = user.identifiers.build({},UserIdentifier.type_to_class(type))
identifier.key = key
yield(user,identifier) if block_given?
end
user
end
def find_or_create_by_external type, key, &blk
find_or_initialize_by_external(type,key,&blk).tap {|u| u.save}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment