This commit is contained in:
Didier Lafforgue 2012-03-08 19:43:42 +01:00
commit 4cccff065a
2 changed files with 30 additions and 14 deletions

View File

@ -1,11 +1,25 @@
module Locomotive
module Liquid
module Tags
# Filter a collection
#
# Usage:
#
# {% with_scope main_developer: 'John Doe', active: true %}
# {% for project in contents.projects %}
# {{ project.name }}
# {% endfor %}
# {% endwith_scope %}
#
class WithScope < ::Liquid::Block
TagAttributes = /(\w+|\w+\.\w+)\s*\:\s*(#{::Liquid::QuotedFragment})/
def initialize(tag_name, markup, tokens, context)
@attributes = {}
markup.scan(::Liquid::TagAttributes) do |key, value|
@attributes = HashWithIndifferentAccess.new
markup.scan(TagAttributes) do |key, value|
@attributes[key] = value
end
super
@ -22,13 +36,7 @@ module Locomotive
def decode(attributes, context)
attributes.each_pair do |key, value|
attributes[key] = (case value
when /^true|false$/i then value == 'true'
when /^[0-9]+$/ then value.to_i
when /^["|'](.+)["|']$/ then $1.gsub(/^["|']/, '').gsub(/["|']$/, '')
else
context[value]
end)
attributes[key] = context[value]
end
end
end

View File

@ -2,25 +2,33 @@ require 'spec_helper'
describe Locomotive::Liquid::Tags::WithScope do
it 'should decode basic options (boolean, interger, ...)' do
it 'decodes basic options (boolean, integer, ...)' do
scope = Locomotive::Liquid::Tags::WithScope.new('with_scope', 'active:true price:42 title:\'foo\' hidden:false', ["{% endwith_scope %}"], {})
attributes = scope.send(:decode, scope.instance_variable_get(:@attributes), {})
attributes = scope.send(:decode, scope.instance_variable_get(:@attributes), ::Liquid::Context.new)
attributes['active'].should == true
attributes['price'].should == 42
attributes['title'].should == 'foo'
attributes['hidden'].should == false
end
it 'should decode context variable' do
it 'decodes more complex options' do
scope = Locomotive::Liquid::Tags::WithScope.new('with_scope', 'price.gt:42.0 price.lt:50', ["{% endwith_scope %}"], {})
attributes = scope.send(:decode, scope.instance_variable_get(:@attributes), ::Liquid::Context.new)
attributes['price.gt'].should == 42.0
attributes['price.lt'].should == 50
end
it 'decodes context variable' do
scope = Locomotive::Liquid::Tags::WithScope.new('with_scope', 'category: params.type', ["{% endwith_scope %}"], {})
attributes = scope.send(:decode, scope.instance_variable_get(:@attributes), { 'params.type' => 'posts' })
attributes = scope.send(:decode, scope.instance_variable_get(:@attributes), ::Liquid::Context.new({ 'params' => { 'type' => 'posts' } }))
attributes['category'].should == 'posts'
end
it 'should store attributes in the context' do
it 'stores attributes in the context' do
template = ::Liquid::Template.parse("{% with_scope active:true title:'foo' %}{{ with_scope.active }}-{{ with_scope.title }}{% endwith_scope %}")
text = template.render
text.should == "true-foo"
end
end