Skip to content

Instantly share code, notes, and snippets.

@nashby
Created September 4, 2011 15:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nashby/1193042 to your computer and use it in GitHub Desktop.
Save nashby/1193042 to your computer and use it in GitHub Desktop.
Gingerbread

##Gingerbread It's like very simple ActiveRecord for Sinatra but uses cookies instead of databases

Use cookies in Sinatra like a boss!

Example:

require './gingerbread'
require 'sinatra'

class Person < Gingerbread
  attribute :name
end

get '/create/:name' do
  person = Person.new(self)
  person.name = params[:name]
  person.save

  'Created!'
end

get '/find/:id' do
  person = Person.find(self, params[:id])

  "Hi, #{person.name}"
end

get '/delete/:id' do
  person = Person.find(self, params[:id])
  person.destroy(self)

  "#{person.name} has been deleted!"
end
class Gingerbread
def initialize(app, attributes = {})
@@app = app
@attributes = attributes
end
def save
if @@app.request.cookies['gingerbread']
data = Marshal.load(@@app.request.cookies['gingerbread'])
else
data = {}
end
data[class_name] ||= {}
@attributes[:id] = next_id(data[class_name])
data[class_name][@attributes[:id]] = self
@@app.response.set_cookie 'gingerbread', :value => Marshal.dump(data), :path => '/'
end
def destroy(app)
data = Marshal.load(app.request.cookies['gingerbread'])
data[class_name].delete(@attributes[:id])
app.response.set_cookie 'gingerbread', :value => Marshal.dump(data), :path => '/'
end
class << self
def attribute(name, value = nil)
define_method(name) do
@attributes[name]
end
define_method("#{name}=") do |value|
@attributes[name] = value
end
end
def find(app, id)
id = id.to_i
if app.request.cookies['gingerbread']
data = Marshal.load(app.request.cookies['gingerbread'])
data[self.to_s.downcase.to_sym] ? data[self.to_s.downcase.to_sym][id] : nil
else
nil
end
end
end
private
def class_name
self.class.to_s.downcase.to_sym
end
def next_id(hash)
id = hash.map{|a, b| a}.max
(id || 0) + 1
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment