2011-05-03 42 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

相關問題