Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if all values for liquid template are provided?

I have liquid templates stored in DB and before rendering, I would like to check, if all params required by the template are provided - by now I found something like:

parsed = Liquid::Template.parse(string_with_template)
required = parsed.instance_values["root"].instance_values["nodelist"].select{ |v| v.is_a?(Liquid::Variable) }.map(&:name)

and then before rendering I have a function

def has_all_required?(liquid_params, required)
  keys = liquid_params.keys
  required.each{|e| return false unless keys.include?(e) }
  return true
end

Is there a cleaner way to achieve this validation?

Thanks for all suggestions, Santuxus

like image 378
santuxus Avatar asked Nov 05 '22 22:11

santuxus


1 Answers

I just did something similar and use a custom validator against my template body when I create the template, eg

validates :body, :presence => true, :email_template => true

then I have a EmailTemplateValidator which validates fields against the template type eg

def validate_each(object, attribute, value)
    case object.template_type
    when 'registration'
        # registration_welcome emails MUST include the activation_url token
        if !value.include?('{{activation_url}}')
            object.errors[attribute] << 'Registration emails must include the {{activation_url}} token'
        end
    end    

end

the plan then is to add new case blocks to the validator as new templates are required in the app with the tokens that they must contain.

like image 106
John Beynon Avatar answered Nov 12 '22 15:11

John Beynon