forked from nesquena/rabl
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Added Rabl::Renderer, a generic rendering class for rendering outside…
… of frameworks
- Loading branch information
1 parent
aa1e614
commit 099047e
Showing
1 changed file
with
30 additions
and
12 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,31 +1,49 @@ | ||
module Rabl | ||
class Renderer < Engine | ||
class Renderer | ||
|
||
attr_reader :file, :object, :options | ||
def initialize(file, object, options = {}) | ||
options = {:format => :json}.update(options) | ||
@file, @object, @options = file, object, options | ||
attr_reader :object, :options | ||
def initialize(source, object = nil, options = {}) | ||
options = { | ||
:format => :json, | ||
:scope => self, | ||
:view_path => [] | ||
}.update(options) | ||
@options = options | ||
|
||
view_path = options.delete(:view_path) | ||
source, location = engine.fetch_source(file, :view_path => view_path) | ||
engine.source = source | ||
@object = object | ||
|
||
engine.source = self.process_source(source) | ||
end | ||
|
||
def render | ||
set_instance_variable(object) | ||
engine.render(self, {}) | ||
def render(scope = nil) | ||
scope = scope ? scope : options.delete(:scope) || self | ||
set_instance_variable(object) if scope == self | ||
engine.render(scope, options.fetch(:locals, {})) | ||
end | ||
|
||
protected | ||
|
||
def engine | ||
@engine ||= Engine.new(nil, options) | ||
@engine ||= Rabl::Engine.new(nil, options) | ||
end | ||
|
||
def process_source(source) | ||
unless source.is_a?(String) && source =~ /\n/ | ||
source, _ = engine.fetch_source(source, {:view_path => options[:view_path]}) | ||
end | ||
return source | ||
end | ||
|
||
def set_instance_variable(object) | ||
name = model_name(object).split('/').last | ||
instance_variable_set(:"@#{name}", object) | ||
end | ||
|
||
def model_name(object) | ||
item = object.is_a?(Array) ? object.first : object | ||
name = item.class.name.underscore | ||
object.is_a?(Array) ? name.pluralize : name | ||
end | ||
|
||
end | ||
end |