Skip to content

Instantly share code, notes, and snippets.

@cchandler
Created April 21, 2010 04:59
Show Gist options
  • Save cchandler/373439 to your computer and use it in GitHub Desktop.
Save cchandler/373439 to your computer and use it in GitHub Desktop.
module CassandraAccess
def self.included(mod)
mod.class_eval do
def cassandra
@@cassandra ||= Cassandra.new(@@keyspace, @@host)
end
def self.cassandra
@@cassandra ||= Cassandra.new(@@keyspace, @@host)
end
def self.cassandra_keyspace(options={})
@@keyspace = options[:keyspace]
@@host = options[:host] || "127.0.0.1:9160"
end
end
end
end
module LittleHelp
def self.included(mod)
mod.class_eval do
@@value_list = []
def self.model_attributes(*val)
@@value_list = val
@@value_list.each do |item|
self.send(:attr_accessor,item)
end
end
def attributes
result = {}
@@value_list.each do |field|
result[field] = self.send(field)
end
result
end
def update_attributes(attributes={})
attributes.each do |i|
self.send("#{i[0]}=", i[1]) if self.respond_to?("#{i[0]}=".to_sym)
end
end
end #end class_eval
end #included?
end
class ApiKey
include Workflow
include CassandraAccess
include Validatable
include LittleHelp
cassandra_keyspace :keyspace => "Heater"
model_attributes :code, :public_read, :key_component, :email, :url, :state, :created_at, :updated_at
validates_presence_of :code, :public_read, :key_component, :state
workflow do
state :initial do
event :upgrade, :transitions_to => :upgraded
event :unlimit, :transitions_to => :unlimited
event :ban, :transitions_to => :suspended
end
state :upgraded do
event :ban, :transitions_to => :suspended
end
state :suspended do
end
state :unlimited
end
def initialize(options={})
update_attributes(options)
@state = "initial" if @state.nil?
end
def self.generate_api_key
api_key = ApiKey.new
api_key.init_keys
api_key.created_at = api_key.updated_at = Time.now.utc.to_s
api_key.email = "[email protected]"
api_key.url = "http://chrischandler.name"
api_key
end
def self.find(id)
ApiKey.new(cassandra.get(:ApiKeys, id))
end
def save
return false unless valid?
local_attributes = self.attributes
local_attributes.reject { |i| i.nil? }
cassandra.insert(:ApiKeys, @code, local_attributes)
cassandra.insert(:ApiKeys, @public_read, local_attributes)
end
def destroy
# TODO Remove object graph
cassandra.remove(:ApiKeys, @code)
cassandra.remove(:ApiKeys, @public_read)
end
def init_keys
@code = rand(10000).to_s
@public_read = rand(10000).to_s
@key_component = rand(10000).to_s
end
protected
def load_workflow_state
@state
end
def persist_workflow_state(new_value)
@state = new_value
## Write to Cassandra
updated_at = Time.now.utc.to_s
cassandra.insert(:ApiKeys, @code, {"state" => @state, "updated_at" => updated_at })
cassandra.insert(:ApiKeys, @public_read, {"state" => @state, "updated_at" => updated_at })
true
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment