Skip to content

Instantly share code, notes, and snippets.

@ess
Created September 30, 2010 01:09
Show Gist options
  • Save ess/603848 to your computer and use it in GitHub Desktop.
Save ess/603848 to your computer and use it in GitHub Desktop.
module Canvas
class Account < Canvas::Model
Canvas::Model.setup
attr_reader :instances
field :id
field :first_name, :required => true
field :last_name, :required => true
field :email, :required => true
field :address, :required => true
field :city, :required => true
field :state, :required => true
field :postal, :required => true
field :country, :required => true
field :organization
field :status
field :aws_access_key
field :aws_secret_access_key
def reload(options={})
self.class.find(self.id)
end
def users
refresh_users if @users.nil?
@users
end
private
def refresh_users
@users = []
response = begin
RestClient.get self.uri(:action => 'users', :id => self.id),
:content_type => :json, :accept => :json
rescue RestClient::Unauthorized
nil
rescue RestClient::ResourceNotFound
nil
end
unless response.nil?
@users = JSON.parse(response.body).collect {|x| User.new(x)}
end
@users
end
def process(attrs = nil)
@instances ||= []
unless attrs.nil?
if attrs.is_a? Hash
(attrs['instances'] || attrs[:instances] || []).each do |i|
@instances.push Instance.new(i)
end
attrs.delete 'instances'
attrs.delete :instances
end
end
super(attrs)
refresh_users
end
end
end
module Canvas
class Instance < Canvas::Model
Canvas::Model.setup
field :id
field :serverid
field :serverimage, :required => true
field :serverflavor, :required => true
field :serveripaddress
field :serverprivateip
field :serverstate
end
end
$ ruby testit.rb
account:
{
"id": "4c89e2450ad0559327000001",
"first_name": "Steven",
"last_name": "Steversen",
"email": "[email protected]",
"address": "123 Any St.",
"city": "Awesomeville",
"state": "MI",
"postal": "48911",
"country": "US",
"organization": "Applied Awesome",
"status": "active",
"aws_access_key": null,
"aws_secret_access_key": null
}
account.instances:
[
"4c986f100ad05530cf000001"
]
account.users:
[
"4c89e2450ad0559327000003"
]
$:.unshift 'lib'
require 'canvas'
Canvas.register_api_key 'THISISCOMPLETELYRANDOM'
account = Canvas::Account.find('4c89e2450ad0559327000001')
puts "account:"
puts JSON.pretty_generate(account.attributes)
puts "account.instances:"
puts JSON.pretty_generate(account.instances.collect {|x| x.id })
puts "account.users:"
puts JSON.pretty_generate(account.users.collect {|x| x.id })
module Canvas
class User < Canvas::Model
Canvas::Model.setup
field :id
field :login, :required => true
field :password
field :api_key
private
def process(attrs)
@account = nil
unless attrs.nil?
if attrs.is_a? Hash
(attrs['account_id'] || attrs[:account_id] || []).each do |i|
@account = Account.new(i)
end
attrs.delete 'account_id'
attrs.delete :account_id
end
end
super(attrs)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment