Skip to content

Instantly share code, notes, and snippets.

@sausman
Created November 23, 2010 07:45
Show Gist options
  • Save sausman/711418 to your computer and use it in GitHub Desktop.
Save sausman/711418 to your computer and use it in GitHub Desktop.
require 'rubygems'
require 'yaml'
require 'rest-client'
require 'rails'
module Seat
# store default database as well as auth credentials in yaml file
CONFIG = YAML::load_file('config.yaml')
# define the RestClient for the Seat module methods to use
@r = RestClient::Resource.new 'http://localhost:'+CONFIG["port"].to_s, CONFIG["user"], CONFIG["pass"]
class Model
# include functionality from ActiveModel
include ActiveModel::Validations
include ActiveModel::Conversion
extend ActiveModel::Naming
# define attributes that every document will have
attr_accessor :_id, :_rev, :type
# define the database that the class will use
# can override with use()
@@db = CONFIG["default"]
@@primary = nil
def initialize(attributes = {})
attributes.each do |name, value|
send("#{name}=", value)
end
@type = self.class.to_s.downcase
# in the future make the code below fire when whatever the primary variable is set
if @_id.nil? && @@primary && self.instance_variable_defined?('@'+@@primary)
@_id = @type+'.'+self.instance_variable_get('@'+@@primary).to_s
end
end
def self.get (id)
u = Seat.get '/'+(@@db||CONFIG["default"])+'/'+self.model_name.downcase+"."+id.to_s
new(ActiveSupport::JSON.decode(u))
end
def self.view (view, args=nil)
# puts "view: #{view}, args: #{args}"
#new(:email=>"testing@gmail.com") # if theres a single record return a Model.new(result)
end
def self.use (db)
@@db = db.to_s
end
def self.primary (key)
@@primary = key.to_s
validates_presence_of key
# make it so when the primary var is changed it changes the ID
end
def save
if self.valid?
remove_instance_variable(:@validation_context)
remove_instance_variable(:@errors)
save = Seat.put '/'+(@@db||CONFIG["default"])+'/'+@_id.to_s, ActiveSupport::JSON.encode(self)
save = ActiveSupport::JSON.decode(save)
@_rev = save["rev"]
else
false
end
end
# used for ActiveModel::Conversion
# tells it whether the model is "persisted"
# in the database (AKA stored)
def persisted?
true
end
#def initialize (atts={})
# atts.each do |a|
# instance_variable_set('@'+a[0].to_s, a[1])
# end
#end
#def method_missing (method, value=nil)
# if method[-1]=="="
# @_errors << "tried to set @"+method.to_s.sub('=', '')+" = "+value
# else
# puts "Method Missing"
# end
#end
end
def Seat.get (url)
begin
@r[url].get
rescue => e
puts e.response
end
end
def Seat.put (url, doc)
begin
@r[url].put doc
rescue => e
puts e.response
end
end
end
class User < Seat::Model
use 'stackd-development'
primary :username
attr_accessor :username, :other, :email
#validates_presence_of :email
#validates_format_of :email, :with => /^[-a-z0-9_+\.]+\@([-a-z0-9]+\.)+[a-z0-9]{2,4}$/i,
# :message => "not a valid email"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment