Skip to content

Instantly share code, notes, and snippets.

@alaibe
Created January 2, 2015 17:37
Show Gist options
  • Save alaibe/bbe2c256b92b9dc66955 to your computer and use it in GitHub Desktop.
Save alaibe/bbe2c256b92b9dc66955 to your computer and use it in GitHub Desktop.
Perpetuity + Virtus creates only one table in pg
require 'perpetuity/postgres'
require 'securerandom'
require 'pp'
require 'virtus'
Perpetuity.data_source :postgres, 'foo', username: 'anthony', host: 'localhost', port: 5432, password: ''
class Entity
include Virtus.model
attribute :id, Integer
end
module Customer
class Account < Entity
attribute :oauth_token, String
attribute :provider, String
end
class User < Entity
attribute :name, String
attribute :email, String
attribute :api_key, String
attribute :accounts, Array[Account]
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:0x007fee33e18ba0 @name="Jamie", @email="jgaskins@gmail.com", @api_key="0ae800b2282fdca5d496d5843b1c0fbc", @accounts=[nil], @id="a9c4ad1c-0fad-4e19-8bbf-83c07b4c3de9">
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment