Skip to content

Instantly share code, notes, and snippets.

@juliocesar
Created May 13, 2010 06:12
Show Gist options
  • Save juliocesar/399552 to your computer and use it in GitHub Desktop.
Save juliocesar/399552 to your computer and use it in GitHub Desktop.
require 'rubygems'
require 'pathname'
require 'rails/all'
class SmallNSexy < Rails::Application
config.session_store :cookie_store, :key => '_omg_session'
config.secret_token = '1319d8ccf1b9bfbdefcb6aa380a044ce'
# ^ because -> http://twitter.com/wycats/status/13898343700
class Page
attr_accessor :name, :body
def self.create name, body
File.open((SmallNSexy.root + 'pages' + name).to_s, 'w') do |file| file << body end
open name
end
def self.open name
new name, File.read((SmallNSexy.root + 'pages' + name).to_s) rescue nil
end
def initialize name, body
@name, @body = name, body
end
def to_json
%Q{{"name": "#{name or 'null'}", "body": "#{body or 'null'}"}}
end
end
module Actions
class << self
def render
lambda do |env|
if page = Page.open(env["action_dispatch.request.path_parameters"][:name])
[200, {'Content-Type' => 'application/x-json'}, [page.to_json]]
else
[404, {'Content-Type' => 'application/x-json'}, ['Page not found!']]
end
end
end
def create
lambda do |env|
vars = env["rack.request.form_hash"]
if vars and vars['name'] and vars['body']
page = Page.create vars['name'], vars['body']
[200, {'Content-Type' => 'application/x-json'}, [page.to_json]]
else
[400, {'Content-Type' => 'application/x-json'}, ['Invalid parameters!'] ]
end
end
end
end
end
end
SmallNSexy.routes.draw do |map|
post '/pages' => SmallNSexy::Actions.create
get '/pages/*name' => SmallNSexy::Actions.render
end
if $0 =~ /spec/
require 'spec'
describe SmallNSexy::Page do
before do `echo page contents >> #{SmallNSexy.root}/pages/example` end
after do `rm -rf #{SmallNSexy.root}/pages/example` end
context 'creation' do
subject { SmallNSexy::Page.create 'bar', 'contents of the page' }
it { should be_a SmallNSexy::Page }
it { subject.name.should == 'bar' }
it { subject.body.should == 'contents of the page'}
end
context 'initializing' do
it 'finds an existing page on Page.open' do SmallNSexy::Page.open('example').should be_a SmallNSexy::Page end
it 'returns nil when a page is not found' do SmallNSexy::Page.open('non').should be_nil end
end
it 'renders a page in [SmallNSexy.root] on #body' do
SmallNSexy::Page.open('example').body.should == "page contents\n"
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment