我在数据库中存储了液体模板,在渲染之前,我想检查一下,是否提供了模板所需的所有参数 - 现在我发现了类似的东西:
parsed = Liquid::Template.parse(string_with_template)
required = parsed.instance_values["root"].instance_values["nodelist"].select{ |v| v.is_a?(Liquid::Variable) }.map(&:name)
然后在渲染之前我有一个函数
def has_all_required?(liquid_params, required)
keys = liquid_params.keys
required.each{|e| return false unless keys.include?(e) }
return true
end
有没有更简洁的方法来实现这种验证?
谢谢大家的建议
圣都士
最佳答案
我只是做了类似的事情,并在创建模板时对我的模板主体使用自定义验证器,例如
validates :body, :presence => true, :email_template => true
然后我有一个 EmailTemplateValidator ,它根据模板类型验证字段,例如
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
结尾
然后计划是向验证器添加新的 case 块,因为应用程序中需要新模板以及它们必须包含的 token 。
关于ruby-on-rails - 如何检查是否提供了液体模板的所有值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5870651/