Skip to content

Commit

Permalink
Merge pull request #131 from Mido-sys/fix_if_condition_if_variable_set
Browse files Browse the repository at this point in the history
return true if the names variable is set
  • Loading branch information
paganotoni authored Apr 15, 2021
2 parents 9f3e607 + 7aec1c0 commit e5e4fe3
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 27 deletions.
13 changes: 0 additions & 13 deletions compiler.go
Original file line number Diff line number Diff line change
Expand Up @@ -200,10 +200,6 @@ func (c *compiler) evalIfExpression(node *ast.IfExpression) (interface{}, error)
}
}

if !c.isValidIfCondtionValue(con) {
return nil, fmt.Errorf("non-bool %s (type %T) used as if condition", node.Condition.String(), con)
}

if c.isTruthy(con) {
return c.evalBlockStatement(node.Block)
}
Expand Down Expand Up @@ -231,16 +227,7 @@ func (c *compiler) evalElseAndElseIfExpressions(node *ast.IfExpression) (interfa
}
return r, nil
}
func (c *compiler) isValidIfCondtionValue(i interface{}) bool {

switch i.(type) {
case bool, nil:
return true

default:
return false
}
}
func (c *compiler) isTruthy(i interface{}) bool {
if i == nil {
return false
Expand Down
33 changes: 19 additions & 14 deletions if_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,20 +6,6 @@ import (
"github.com/stretchr/testify/require"
)

func Test_Render_If_Condition_Not_Valid(t *testing.T) {
r := require.New(t)
input := `<%
if (x - 4) {
return "hi"
} %>`
ctx := NewContext()
ctx.Set("x", 4)

s, err := Render(input, ctx)
r.Error(err)
r.Equal("", s)
}
func Test_Render_If(t *testing.T) {
r := require.New(t)
input := `<% if (true) { return "hi"} %>`
Expand Down Expand Up @@ -255,3 +241,22 @@ func Test_If_String_Truthy(t *testing.T) {
r.NoError(err)
r.Equal("<p>hi</p>", s)
}

func Test_Render_If_Variable_Is_Set(t *testing.T) {
r := require.New(t)
input := `<%= if (names) { %>hi<%} %>`
ctx := NewContext()
ctx.Set("names", "123")
s, err := Render(input, ctx)
r.NoError(err)
r.Equal("hi", s)
}

func Test_Render_If_Variable_Not_Set(t *testing.T) {
r := require.New(t)
input := `<%= if (names) { %>hi<%} %>`

s, err := Render(input, NewContext())
r.NoError(err)
r.Equal("", s)
}

0 comments on commit e5e4fe3

Please sign in to comment.