Skip to content

Instantly share code, notes, and snippets.

@reactormonk
Forked from botanicus/rest.rb
Created March 23, 2010 11:54
Show Gist options
  • Save reactormonk/341089 to your computer and use it in GitHub Desktop.
Save reactormonk/341089 to your computer and use it in GitHub Desktop.
class RESTController < Controller
def self.object_name=(object_name)
@@object_name = object_name
end
def self.object_name
@@object_name
end
# @api plugin
def object_name
@@object_name
end
def collection_name
@@collection_name ||= "#{@@object_name}s"
end
def self.template_root=(template_root)
@@template_root = template_root
end
def self.template_root
@@template_root
end
# @api plugin
def template_root
@@template_root
end
def self.define_rest_method(method)
define_method method do |&block|
raise ArgumentError, "You have to provide a block" if block.nil?
context[collection_name] = block.call
render File.join(template_root, index)
end
end
[:index, :show, :new, :edit].each(&:define_rest_method)
def create(notice = "Created successfully", error = "Can't create", &block)
raise ArgumentError, "You have to provide a block" if block.nil?
object = block.call
if object.save
message[:notice] = notice
redirect # TODO
else
message[:error] = error
redirect # TODO
end
end
def update(notice = "Updated successfully", error = "Can't update", &block)
raise ArgumentError, "You have to provide a block" if block.nil?
object = block.call
if object.save
message[:notice] = notice
redirect # TODO
else
message[:error] = error
redirect # TODO
end
end
end
class Posts < RESTController
object_name :post
template_root "blog/posts"
def index(page)
super do
Post.paginate(page, 20)
end
end
def show(id)
super { Post.get(id) }
end
def new
super { Post.new }
end
def edit(id)
super { @post || Post.get(id) }
end
def create(post)
notice = "Post create successfuly"
error = "Saving failed"
super(notice, error) do
@post = Post.new(post)
end
end
def update(id, post)
super do
@post = Post.attributes.merge!(post)
end
end
end
class MyCustomizedPosts < Posts
def create(post)
super(post)
rescue Rango::Exceptions::Redirection
redirect "/"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment