Skip to content

Commit

Permalink
tweak filter func
Browse files Browse the repository at this point in the history
  • Loading branch information
vincerubinetti committed Aug 29, 2024
1 parent 548dfeb commit 0152de7
Showing 1 changed file with 10 additions and 10 deletions.
20 changes: 10 additions & 10 deletions _plugins/misc.rb
Original file line number Diff line number Diff line change
Expand Up @@ -18,17 +18,17 @@ def object_items(object)
return object
end

# filter a list of hashes by comma-sep'd field:value pairs

def empty_binding
binding
end

# make arbitrary string into valid ruby variable name
def safe_var_name(name)
return name.to_s.gsub /[^a-z]+/, "_"
return name.to_s.gsub(/[^a-z]+/i, "_").gsub(/^_|_$/, "")
end

# jekyll ruby plugin
# filter a list of hashes
def data_filter(data, filter)
if not filter.is_a?(String)
return data
Expand All @@ -37,14 +37,14 @@ def data_filter(data, filter)
# filter data
return data.clone.select{
|item|
# start with empty context of local variables
b = empty_binding
# add item as local variable
b.local_variable_set("item", item)
# if jekyll doc collection, get hash of doc data
if item.is_a? Jekyll::Document
item = item.data
end
# start with empty context of local variables
b = empty_binding
# add item as local variable
b.local_variable_set("item", item)
# also set each item field as local variable when evaluating filter
item.each do |var, val|
b.local_variable_set(safe_var_name(var), val)
Expand All @@ -53,12 +53,12 @@ def data_filter(data, filter)
keep = true
while true
begin
# evaluate filter code, coerce to true/false
# evaluate expression as true/false
keep = !!eval(filter, b)
# if no error, done
break
# if a var in expression isn't a field on item
rescue NameError => e
# if var in filter doesn't exist, define it and re-evaluate
# define it and re-evaluate
b.local_variable_set(safe_var_name(e.name), nil)
end
end
Expand Down

0 comments on commit 0152de7

Please sign in to comment.