Sha256: b9a99ffed1427bc11f18e5dd90bea95a865656ddf4b42a5d4a715113e2efe83b

Contents?: true

Size: 1.65 KB

Versions: 2

Compression:

Stored size: 1.65 KB

Contents

module Cell
  # Gets cached in production.
  class Templates
    # prefixes could be instance variable as they will never change.
    def [](prefixes, view, engine, formats=nil)
      view = "#{view}.#{engine}"

      find_template(prefixes, view, engine)
    end

  private

    def cache
      @cache ||= Cache.new
    end

    def find_template(prefixes, view, engine)
      cache.fetch(prefixes, view) do |prefix|
        # this block is run once per cell class per process, for each prefix/view tuple.
        create(prefix, view)
      end
    end

    def create(prefix, view)
      # puts "...checking #{prefix}/#{view}"
      return unless File.exists?("#{prefix}/#{view}") # DISCUSS: can we use Tilt.new here?
      Tilt.new("#{prefix}/#{view}", escape_html: false, escape_attrs: false)
    end

    # {["comment/row/views", comment/views"][show.haml] => "Tpl:comment/view/show.haml"}
    class Cache
      def initialize
        @store = {}
      end

      # Iterates prefixes and yields block. Returns and caches when block returned template.
      # Note that it caches per prefixes set as this will most probably never change.
      def fetch(prefixes, view)
        template = get(prefixes, view) and return template # cache hit.

        prefixes.find do |prefix|
          template = yield(prefix) and return store(prefixes, view, template)
        end
      end

    private
      # ["comment/views"] => "show.haml"
      def get(prefixes, view)
        @store[prefixes] ||= {}
        @store[prefixes][view]
      end

      def store(prefix, view, template)
        @store[prefix][view] = template # the nested hash is always present here.
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
cells-4.0.0.beta5 lib/cell/templates.rb
cells-4.0.0.beta4 lib/cell/templates.rb