Repository navigation
ActiveRecord
If you include Spigot on an ActiveRecord class, you get a few more methods.
This uses the primary key defined in that resource's options to query the database with the value taken from the api data. (Note Does not update any values on the record received from the database.)
# Spigot definition
Spigot.resource(:user) do
full_name :name
login :email
token :auth
options do
primary_key :email
end
end
# API Data
data = {"full_name":"Dean","login":"dino@amore.io","token":"bcd456"}
#=> User.find_by_api(data)
User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."email" = 'dino@amore.io' ORDER BY "users"."id" ASC LIMIT 1
#=> #<User id: 1, name: "Dean Martin", email: "dino@amore.io", token: "abc123">
Operates just like find_by_api, but returns all matches on the primary key. The method
returns an ActveRecord::Relation allowing you to chain other constraints if you need.
Spigot.resource(:user) do
full_name :name
login :email
token :auth
options do
primary_key :full_name
end
end
# API Data
data = {"full_name":"Dean","login":"dino@amore.io","token":"bcd456"}
#=> User.find_all_by_api(data)
User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."name" = 'Dean'
=> #<ActiveRecord::Relation [#<User id: 1, name: "Dean", email: "dino@amore.io", token: "abc123">, #<User id: 2, name: "Dean", email: "minerals@notrocks.io", token: '92fnd'>]>
Creates a record in your database using the provided API data, without doing any kind of query before, beyond your model's defined validations. Notice the creation does not use any of the API that isn't defined in the map.
Spigot.resource(:user) do
full_name :name
login :email
token :auth
options do
primary_key :email
end
end
# API Data
data = {"full_name":"Frank Sinatra","login":"live@tilidie.io","id":"3"}
#=> User.create_by_api(data)
SQL (0.1ms) INSERT INTO "users" ("name", "email") VALUES (?, ?) [["name", "Frank Sinatra"], ["email", "live@tilidie.io"]]
=> #<User id: 4, name: "Frank Sinatra", email: "live@tilidie.io", token: nil>
Updates a record in your database. If no record matching the primary key is found, nothing happens.
Spigot.resource(:user) do
full_name :name
login :email
token :auth
options do
primary_key :email
end
end
# API Data
data = {"full_name":"Dino Baby","login":"dean@amore.io","token":"bcd456"}
#=> User.update_by_api(data)
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."email" = 'livetilidie' ORDER BY "active_users"."id" ASC LIMIT 1
SQL (0.1ms) UPDATE "users" SET "name" = ?, token = ? WHERE "users"."id" = 3 [["name", "Dino Baby"], ["token", "bcd456"]]
=> #<User id: 3, name: "Dino Baby", email: "dean@amore.io", token: "bcd456">
Query the database to find an existing record. If none is found, create one with the provided API data.
Query the database to find an existing record. If a record is found, update the record with the received API data. If no record is found, create one with the provided API data.