Skip to content

Instantly share code, notes, and snippets.

@jamiehodge
Last active December 10, 2015 23:28
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 jamiehodge/4509675 to your computer and use it in GitHub Desktop.
Save jamiehodge/4509675 to your computer and use it in GitHub Desktop.
Decoupling Webmachine dispatcher and resource life cycles
# Please ignore this solution. It's too complicated :-(
require "webmachine"
class MyResource
include Webmachine::Resource::Callbacks
include Webmachine::Resource::Tracing
attr_reader :model, :request, :response
def initialize(args={})
@model = args.fetch(:model, Object)
@request = args.fetch(:request)
@response = args.fetch(:response)
end
def to_html
model.class.to_s
end
end
# Allow duck typing
class Webmachine::Dispatcher::Route
def initialize(path_spec, *args)
if args.last.is_a? Hash
bindings = args.pop
else
bindings = {}
end
resource = args.pop
guards = args
guards << Proc.new if block_given?
@path_spec = path_spec
@guards = guards
@resource = resource
@bindings = bindings
end
end
Mock = Class.new
App = Webmachine::Application.new do |app|
app.routes do
add [], MyResource
self.resource_creator = ->(route, request, response) do
route.resource.new(model: Mock.new, request: request, response: response)
end
end
end.run
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment