Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions lib/hypertemplate/builder.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ module Hypertemplate
module Builder
require "hypertemplate/builder/base"
require "hypertemplate/builder/values"
require "hypertemplate/builder/cache"
require "hypertemplate/builder/json"
require "hypertemplate/builder/xml"

Expand Down
15 changes: 14 additions & 1 deletion lib/hypertemplate/builder/base.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,14 @@ class Base
undef_method :id if respond_to?(:id)

class << self

def cache
@cache
end

def cache=(cache)
@cache = cache
end

def media_types
@media_types
end
Expand Down Expand Up @@ -98,6 +105,12 @@ def ns(*args, &block)
end
end

def cache(key)
Cache.new(key, self) do |cache|
yield cache
end
end

# writes a key and value pair to the representation
# example:
#
Expand Down
49 changes: 49 additions & 0 deletions lib/hypertemplate/builder/cache.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
module Hypertemplate
module Builder
class Cache #< BasicObject
attr_accessor :builder

def initialize(key, builder, &block)
@key = key
@builder = builder

if cached?
raw = cache.read(cache_key)

if builder.class == Xml
data = Nokogiri::XML(raw)
else
data = MultiJson.decode(raw)
end
else
_builder = builder.class.new({})
yield _builder
data = _builder.raw

cache.write(cache_key, _builder.representation)
end

if current = builder.instance_variable_get('@current') # JSON
current.merge!(data)
else # XML
parent = builder.instance_variable_get('@parent')
data.root.children.each do |element|
element.parent = parent
end
end
end

def cached?
cache.exist?(cache_key)
end

def cache
Hypertemplate::Builder::Base.cache
end

def cache_key
@_generated_key ||= "#{@key}_#{builder.class.to_s.split('::').last}"
end
end
end
end
2 changes: 1 addition & 1 deletion lib/hypertemplate/builder/json.rb
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ def insert_value(name, prefix, *args, &block)
end

def representation
@raw.to_json
MultiJson.encode(@raw)
end

private
Expand Down
6 changes: 6 additions & 0 deletions lib/hypertemplate/hook/rails.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
require 'hypertemplate' unless defined? ::Hypertemplate

module Hypertemplate
class Railtie < Rails::Railtie
initializer "hypertemplate.setup_cache" do
Hypertemplate::Builder::Base.cache = Rails.cache
end
end

module RegistryContainer

def hypertemplate_registry
Expand Down