2011-05-03 52 views
5

我已经存储在数据库和渲染之前液体的模板,我想检查一下,如果所有PARAMS要求的模板提供了 - 现在我发现这样的:如何检查是否提供液体模板的所有值?

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 

是否有更简单的方法来实现此验证?

感谢所有的建议, Santuxus

回答

1

我只是做了类似的事情,并使用自定义验证程序对我的模板的身体,当我创建模板,如

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  

领域

然后,计划将向验证程序添加新的大小写块,因为应用程序需要使用它们必须包含的令牌的新模板。

+0

问题是模板可以在管理面板中编辑,所以我需要一个通用的方法 - 如果我知道所有必需的值,我可以用你的方法,谢谢你的答案;)我的意思是例如: page_title可以具有以下价值:“这是{{product_name}}”,后来更改为“这是价格{{product_price}}'的{{product_name}}”。 – santuxus 2011-05-03 14:20:31