Skip to content

Commit

Permalink
use Tables interface when possible for DataFrames; re-organize tests (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
jverzani authored Dec 10, 2018
1 parent e0514f5 commit 9aedfcc
Show file tree
Hide file tree
Showing 5 changed files with 68 additions and 67 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@ _names = String[]
_summaries = String[]
for s in sort(map(string, names(Main)))
v = Symbol(s)
if isdefined(m,v)
if isdefined(Main,v)
push!(_names, s)
push!(_summaries, summary(eval(v)))
end
Expand Down
53 changes: 35 additions & 18 deletions src/context.jl
Original file line number Diff line number Diff line change
Expand Up @@ -86,14 +86,19 @@ end
## This of course varies based on the view.
## we special case dataframes here, so that we don't have to assume package is loaded
function lookup_in_view(view, key)
if is_dataframe(view)
if occursin(r":", key) key = key[2:end] end
if Tables.istable(view)
r = first(Tables.rows(view))
if occursin(r"^:", key) key = key[2:end] end
k = Symbol(key)
k in propertynames(r) ? getproperty(r, k) : nothing
elseif is_dataframe(view)
if occursin(r"^:", key) key = key[2:end] end
key = Symbol(key)
out = nothing
if haskey(view, key)
out = view[1, key] ## first element only
out = view[1, key] ## first element only
end
return out
out
else
_lookup_in_view(view, key)
end
Expand Down Expand Up @@ -141,22 +146,34 @@ function _lookup_in_view(view::Module, key)

end

## Default is likely not great, but we use CompositeKind
## Default is likely not great,
function _lookup_in_view(view, key)
nms = fieldnames(typeof(view))
re = Regex(key)
has_match = false
for i in nms
if occursin(Regex(key), string(i))
has_match=true
break
end
end

out = nothing
if has_match
out = getfield(view, Symbol(key)) ## view.key
if occursin(r"^:", key)
k = Symbol(key[2:end])
else
k = key
end

out
# check propertyname, then fieldnames
if k in propertynames(view)
getproperty(view, k)
else

nms = fieldnames(typeof(view))

# we match on symbol or string for fieldname
if isa(k, Symbol)
has_match = k in nms
else
has_match = Symbol(k) in nms
end

out = nothing
if has_match
out = getfield(view, Symbol(k)) ## view.key
end

out
end
end
10 changes: 5 additions & 5 deletions src/tokens.jl
Original file line number Diff line number Diff line change
Expand Up @@ -432,14 +432,14 @@ end

# render tokens with values given in context
function renderTokensByValue(value, io, token, writer, context, template, args...)
if is_dataframe(value) # XXX remove once istable(x::DataFrame) == true works
for i in 1:size(value)[1]
renderTokens(io, token.collector, writer, ctx_push(context, value[i,:]), template, args...)
end
elseif Tables.istable(value)
if Tables.istable(value)
for row in Tables.rows(value)
renderTokens(io, token.collector, writer, ctx_push(context, row), template, args...)
end
elseif is_dataframe(value) # XXX remove once istable(x::DataFrame) == true works
for i in 1:size(value)[1]
renderTokens(io, token.collector, writer, ctx_push(context, value[i,:]), template, args...)
end
else
inverted = token._type == "^"
if (inverted && falsy(value)) || !falsy(value)
Expand Down
26 changes: 17 additions & 9 deletions test/Mustache_test.jl
Original file line number Diff line number Diff line change
Expand Up @@ -64,11 +64,6 @@ tpl = mt"{{#:d}}{{x}} and {{y}}{{/:d}}"
d = Dict(); d["x"] = "salt"; d["y"] = "pepper"
@test Mustache.render(tpl, d=d) == "salt and pepper"

## issue #51 inverted section
@test Mustache.render("""{{^repos}}No repos :({{/repos}}""", Dict("repos" => [])) == "No repos :("
@test Mustache.render("{{^repos}}foo{{/repos}}",Dict("repos" => [Dict("name" => "repo name")])) == ""


## Added a new tag "|" for applying a function to a section
tpl = """{{|lambda}}{{value}}{{/lambda}} dollars."""
d = Dict("value"=>"1.23456789", "lambda"=>(txt) -> "<b>" * string(round(parse(Float64, txt), digits=2)) * "</b>")
Expand Down Expand Up @@ -128,7 +123,20 @@ filepath = joinpath(@__DIR__, "test-sections-crlf.tpl")
@test Mustache.render_from_file(filepath, Dict("a"=>Dict("x"=>111,),)) == " 111\r\n"
@test Mustache.render_from_file(filepath, Dict("y"=>222,)) == " 222\r\n"

## Issue 88
template = "{{#:vec}}{{.}}{{^.[end]}},{{/.[end]}}{{/:vec}}";
@test render(template, vec=["a", "b", "c"]) == "a,b,c"
@test render(template, vec=fill("a", 3)) == "a,a,a"
@testset "closed issues" begin

## issue #51 inverted section
@test Mustache.render("""{{^repos}}No repos :({{/repos}}""", Dict("repos" => [])) == "No repos :("
@test Mustache.render("{{^repos}}foo{{/repos}}",Dict("repos" => [Dict("name" => "repo name")])) == ""


## Issue #80 with 0 as falsy
tpl = "this is {{:zero}}"
@test render(tpl, zero=0) == "this is 0"


## Issue 88
template = "{{#:vec}}{{.}}{{^.[end]}},{{/.[end]}}{{/:vec}}";
@test render(template, vec=["a", "b", "c"]) == "a,b,c"
@test render(template, vec=fill("a", 3)) == "a,a,a"
end
44 changes: 10 additions & 34 deletions test/data-frame-test.jl
Original file line number Diff line number Diff line change
Expand Up @@ -2,39 +2,19 @@
## not run by default. Too time consuming and relies on external pacakgs
using Mustache, DataFrames
using Test

glm_tpl = mt"""
\begin{table}
\begin{tabular}{l @{\quad} rrrr}
{{#colnms}}
&\verb+{{{colnm}}}+
{{/colnms}}\\
{{#mat}}
{{variable}} & {{col1}} & {{col2}} & {{col3}} & {{col4}}\\
{{/mat}}
\end{tabular}
\end{table}
using Printf

# simple usage
tpl = mt"""
{{:TITLE}}
{{#:D}}
{{:english}} <--> {{:spanish}}
{{/:D}}
"""

function glm_table(mod)
tbl = coeftable(mod)

colnms = DataFrame(colnm=tbl.colnms)
mat = DataFrame(variable=tbl.rownms)
for j in 1:size(tbl.mat)[2]
nm = "col$j"
mat[Symbol(nm)] = map(x -> @sprintf("%.2f", x), tbl.mat[:,j])
end

Mustache.render(glm_tpl,Dict("colnms"=>colnms, "mat"=>mat))
end
d = DataFrame(english=["hello", "good bye"], spanish=["hola", "adios"])



using GLM, RDatasets, DataFrames
LifeCycleSavings = dataset("datasets", "LifeCycleSavings")
fm2 = fit(LinearModel, SR ~ Pop15 + Pop75 + DPI + DDPI, LifeCycleSavings)
glm_table(fm2)
@test render(tpl, TITLE="translate", D=d) == "translate\nhello <--> hola\ngood bye <--> adios\n"


## Issue with data frames as keyword arguments
Expand All @@ -44,7 +24,3 @@ tpl = """
"""
d = DataFrame(a=[1,2,3], b=[3,2,1])
@test render(tpl, fred=d, barney="123") == "1--32--23--1\n123\n"

## Issue #80 with 0 as falsy
tpl = "this is {{:zero}}"
@test render(tpl, zero=0) == "this is 0"

0 comments on commit 9aedfcc

Please sign in to comment.