Merge pull request #4 from ccocchi/responder

Add custom responder
This commit is contained in:
Christopher Cocchi-Perrier 2012-09-11 02:53:15 -07:00
commit 5ca0a44241
3 changed files with 40 additions and 5 deletions

View File

@ -1,5 +1,8 @@
# CHANGELOG # CHANGELOG
## 0.1.3 (unreleased)
* Add custom Responder
## 0.1.2 ## 0.1.2
* Add RablRails#render method (see README or source code) * Add RablRails#render method (see README or source code)
* Fix fail when JSON engine is not found. Now fallback to MultiJson.default_adapter * Fix fail when JSON engine is not found. Now fallback to MultiJson.default_adapter

View File

@ -17,31 +17,41 @@ require 'multi_json'
module RablRails module RablRails
extend Renderer extend Renderer
autoload :Responder, 'rabl-rails/responder'
mattr_accessor :cache_templates mattr_accessor :cache_templates
@@cache_templates = true @@cache_templates = true
mattr_accessor :include_json_root mattr_accessor :include_json_root
@@include_json_root = true @@include_json_root = true
mattr_reader :json_engine mattr_reader :json_engine
@@json_engine = :yajl @@json_engine = :yajl
mattr_accessor :use_custom_responder
@@use_custom_responder = false
mattr_accessor :responder_default_template
@@responder_default_template = 'show'
def self.configure def self.configure
yield self yield self
ActionController::Base.responder = Responder if self.use_custom_responder
end end
def self.json_engine=(name) def self.json_engine=(name)
MultiJson.engine = name MultiJson.engine = name
@@json_engine = name @@json_engine = name
rescue LoadError rescue LoadError
Rails.logger.warn %Q(WARNING: rabl-rails could not load "#{self.json_engine}" as JSON engine, fallback to default) Rails.logger.warn %Q(WARNING: rabl-rails could not load "#{self.json_engine}" as JSON engine, fallback to default)
end end
def self.cache_templates? def self.cache_templates?
ActionController::Base.perform_caching && @@cache_templates ActionController::Base.perform_caching && @@cache_templates
end end
def self.load_default_engines! def self.load_default_engines!
self.json_engine = :yajl self.json_engine = :yajl
end end

View File

@ -0,0 +1,22 @@
module RablRails
#
# Override default responder's api behavior to not
# user to_format methods on a resource as a default
# representation but instead use a rabl template
#
class Responder < ActionController::Responder
protected
def api_behavior(error)
rabl_options = options.merge(template: RablRails.responder_default_template)
if get?
controller.default_render rabl_options
elsif post?
controller.default_render rabl_options.merge!(status: :created, location: api_location)
else
head :no_content
end
end
end
end