Permalink
Browse files

Basic rendering working

  • Loading branch information...
1 parent 497c2ba commit 7a802fc23c9c2463dd7dca92de92b9d8c86bcb01 @paul committed Feb 9, 2010
Showing with 109 additions and 2 deletions.
  1. +67 −0 lib/rest-json-template.rb
  2. +41 −2 spec/rest-json-template_spec.rb
  3. +1 −0 spec/spec_helper.rb
View
@@ -0,0 +1,67 @@
+require 'active_support/ordered_hash'
+require 'tilt'
+require 'yajl'
+
+
+module RestJson
+
+ class Template < Tilt::Template
+
+ def compile!
+ end
+
+ def evaluate(scope, locals, &block)
+ scope.instance_eval(data)
+ end
+ end
+ Tilt.register('restjson', Template)
+
+ module Helper
+ def restjson_for(resource, &blk)
+ builder = RestJson::Builder.new(resource)
+ yield builder
+ builder.render
+ end
+ end
+
+ class Builder
+
+ def initialize(resource)
+ @resource = resource
+ @attributes = ActiveSupport::OrderedHash.new
+ set_keys!
+ end
+
+ def set_keys!
+ @attributes[:_type] = @resource.class.to_s.split('::').last
+ end
+
+ def href(href)
+ @attributes[:href] = href
+ end
+
+ def attributes(*keys)
+ keys = keys.flatten
+ if keys.first.is_a?(Hash)
+ @attributes.merge!(keys.first)
+ else
+ keys.each do |name|
+ @attributes[name] = @resource.send(name)
+ end
+ end
+ end
+ alias attribute attributes
+
+ def link_to(name, url)
+ name = name.to_s
+ name << "_href" unless name =~ /_href\Z/
+ attribute(name => url)
+ end
+
+ def render
+ Yajl::Encoder.encode(@attributes)
+ end
+
+ end
+
+end
@@ -1,7 +1,46 @@
require File.expand_path(File.dirname(__FILE__) + '/spec_helper')
describe "RestJsonTemplate" do
- it "fails" do
- fail "hey buddy, you should probably rename this file and start specing for real"
+
+ class Article < Struct.new(:id, :title, :text); end
+
+ class Scope
+ include RestJson::Helper
+ end
+
+ def scope
+ scope = Scope.new
+ scope.instance_variable_set(:@article, article)
+ scope
+ end
+
+ def article
+ @article = Article.new(42, "The Answer", "Life, the Universe, and Everything")
end
+
+ def data
+ @data ||= File.read(__FILE__).split("\n__END__\n").last
+ end
+
+ def template
+ @template ||= RestJson::Template.new('test.json.restjson') { data }
+ end
+
+
+ it 'should do something' do
+ text = template.render(scope)
+ pp text
+ end
+
+end
+
+__END__
+restjson_for(@article) do |json|
+
+ json.href "http://example.com/articles/#{@article.id}"
+
+ json.attributes :title, :text
+
+ json.link_to :comments, "http://example.com/articles/#{@article.id}/comments"
+
end
View
@@ -3,6 +3,7 @@
require 'rest-json-template'
require 'spec'
require 'spec/autorun'
+require 'pp'
Spec::Runner.configure do |config|

0 comments on commit 7a802fc

Please sign in to comment.