Last active
August 29, 2015 14:12
-
-
Save jgaskins/7d1110fb77b45da4e39e to your computer and use it in GitHub Desktop.
Example displaying eager loading with perpetuity-postgres for https://github.com/jgaskins/perpetuity-postgres/issues/18
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'perpetuity/postgres' | |
require 'securerandom' | |
require 'pp' | |
Perpetuity.data_source 'postgres://localhost/customer_stuff' | |
module Customer | |
class User | |
attr_accessor :name, :email, :api_key, :accounts | |
def initialize attributes={} | |
@name = attributes[:name] | |
@email = attributes[:email] | |
@api_key = attributes[:api_key] | |
@accounts = attributes.fetch(:accounts) { [] } | |
end | |
end | |
class Account | |
attr_accessor :oauth_token, :provider | |
def initialize attributes={} | |
@oauth_token = attributes[:oauth_token] | |
@provider = attributes[:provider] | |
end | |
end | |
end | |
Perpetuity.generate_mapper_for Customer::User do | |
attribute :name, type: String | |
attribute :email, type: String | |
attribute :api_key, type: String | |
attribute :accounts | |
index :api_key | |
end | |
Perpetuity.generate_mapper_for Customer::Account do | |
attribute :oauth_token, type: String | |
attribute :provider, type: String | |
index :oauth_token | |
end | |
account = Customer::Account.new(oauth_token: SecureRandom.hex, | |
provider: 'linkedtwitface') | |
me = Customer::User.new(name: 'Jamie', | |
email: 'jgaskins@gmail.com', | |
api_key: SecureRandom.hex, | |
accounts: [account]) | |
user_mapper = Perpetuity[Customer::User] | |
id = user_mapper.insert(me) | |
retrieved_user = user_mapper.find(id) | |
user_mapper.load_association! retrieved_user, :accounts | |
pp retrieved_user | |
# #<Customer::User:0x007f92f82ea788 | |
# @accounts= | |
# [#<Customer::Account:0x007f92f82e8f28 | |
# @id="6a0c96d2-0f13-4daf-a946-695059384f29", | |
# @oauth_token="e8650ccd5960a26cf0785d9a40273e36", | |
# @provider="linkedtwitface">], | |
# @api_key="e1fa7b308d610a33bb9bdba9c6f7373a", | |
# @email="jgaskins@gmail.com", | |
# @id="8186c56c-d5db-4c3d-85d0-39e9bd362fcf", | |
# @name="Jamie"> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment