Skip to content

Instantly share code, notes, and snippets.

@drogus
Created April 23, 2012 18:34
Show Gist options
  • Save drogus/2472931 to your computer and use it in GitHub Desktop.
Save drogus/2472931 to your computer and use it in GitHub Desktop.
Webmachine + ActionView pt2
class AbstractResource < Webmachine::Resource
include ActionView::Context
private
def paths
ActionView::PathSet.new(["views"])
end
def lookup_context
@_lookup_context ||= begin
ActionView::LookupContext.new(paths)
end
end
def renderer
@_renderer ||= ActionView::Renderer.new(lookup_context)
end
end
require 'bundler/setup'
require 'webmachine'
require 'action_view'
$:.unshift(".")
require 'page'
require 'abstract_resource'
class PageResource < AbstractResource
include ActionView::Context
def resource_exists?
@page = Page.first(:slug => request.path_info[:slug])
@page.present?
end
def title
@page.title
end
def content
@page.content
end
def to_html
renderer.render(self, :template => "page")
end
end
require 'webmachine/adapters/rack'
App = Webmachine::Application.new do |app|
app.configure do |config|
config.adapter = :Rack
end
app.routes do
add [:slug], PageResource
add [], PageResource, :slug => "__root"
end
end
App.run
source "http://rubygems.org"
gem "webmachine"
gem "actionpack"
gem "thin"
gem "datamapper"
gem "dm-migrations"
gem "dm-sqlite-adapter"
gem "debugger"
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
</head>
<body>
<h1><%= title %></h1>
<article><%= content %></article>
</body>
</html>
require 'data_mapper'
require 'dm-migrations'
DataMapper.setup(:default, 'sqlite::memory:')
class Page
include DataMapper::Resource
property :id, Serial
property :title, String
property :slug, String
property :content, Text
end
DataMapper.finalize
DataMapper.auto_migrate!
Page.create(:title => "This is cool!",
:slug => "this-is-cool",
:content => "Yup, very cool")
Page.create(:title => "Main page",
:slug => "__root",
:content => "main page content")
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
</head>
<body>
<h1><%= title %></h1>
<article><%= content %></article>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment