From 3c3eb2f7e71a4db01d0a281ff5ab7e6a9c1f607b Mon Sep 17 00:00:00 2001
From: Holger Just <h.just@finn.de>
Date: Mon, 26 Dec 2011 13:12:05 +0100
Subject: [PATCH] [#790] Register variables with an API

---
 app/helpers/application_helper.rb     |  2 +-
 lib/chili_project/liquid/variables.rb | 32 +++++++++++++++++++++------
 2 files changed, 26 insertions(+), 8 deletions(-)

diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb
index 085ea2a01..8f8331593 100644
--- a/app/helpers/application_helper.rb
+++ b/app/helpers/application_helper.rb
@@ -472,7 +472,7 @@ module ApplicationHelper
       liquid_variables = get_view_instance_variables_for_liquid
       liquid_variables.merge!({'current_user' => User.current})
       liquid_variables.merge!({'toc' => '{{toc}}'}) # Pass toc through to replace later
-      liquid_variables.merge!(ChiliProject::Liquid::Variables.macro_backwards_compatibility)
+      liquid_variables.merge!(ChiliProject::Liquid::Variables.all)
 
       # Pass :view in a register so this view (with helpers) can be used inside of a tag
       text = liquid_template.render(liquid_variables, :registers => {:view => self, :object => obj, :attribute => attr})
diff --git a/lib/chili_project/liquid/variables.rb b/lib/chili_project/liquid/variables.rb
index 83fea34ab..fc1c37bbd 100644
--- a/lib/chili_project/liquid/variables.rb
+++ b/lib/chili_project/liquid/variables.rb
@@ -15,14 +15,32 @@
 module ChiliProject
   module Liquid
     module Variables
-      # Liquid "variables" that are used for backwards compatability with macros
-      #
-      # Variables are used in liquid like {{var}}
-      def self.macro_backwards_compatibility
-        {
-          'macro_list' => "Use the '{% variable_list %}' tag to see all Liquid variables and '{% tag_list %}' to see all of the Liquid tags."
-        }
+      class LazyVariable
+        def initialize(context, &block)
+          @block = block
+          @context = context
+        end
+
+        def to_liquid()
+          (@block.arity == 0) ? @block.call : @block.call(@context)
+        end
+      end
+
+      # Register a Liquid variable.
+      # Pass a value to register a fixed variable or a block to create a lazy
+      # evaluated variable. The block can take the current context
+      def self.register(name, value=nil, &block)
+        var = block_given? ? Proc.new(){|ctx| LazyVariable.new(ctx, &block)} : value
+        all[name.to_s] = var
       end
+
+      def self.all
+        @variables ||= {}
+      end
+
+      # DEPRACATED: This is just a hint on how to use Liquid introspection
+      register "macro_list",
+        "Use the '{% variable_list %}' tag to see all Liquid variables and '{% tag_list %}' to see all of the Liquid tags."
     end
   end
 end
-- 
GitLab