Module: ActiveRecord::Validations::ClassMethods

Defined in:
lib/liquid_loader/liquid_validations.rb

Instance Method Summary collapse

Instance Method Details

#validates_liquid_of(*attr_names) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/liquid_loader/liquid_validations.rb', line 4

def validates_liquid_of(*attr_names)
  configuration = { :message => I18n.translate('activerecord.errors.messages')[:invalid], :on => :save }
  configuration.update(attr_names.extract_options!)

  validates_each(attr_names, configuration) do |record, attr_name, value|
    errors = []
    
    begin
      template = Liquid::Template.parse(value.to_s)
      errors  += template.errors
    rescue Exception => e
      errors << e.message
    end    
    
    for error in errors
      record.errors.add_to_base(friendly_liquid_error(error) + " in your #{ friendly_attr_name(attr_name) }")
    end
    
  end    
end

#validates_presence_of_liquid_variable(*attr_names) ⇒ Object

Raises:

  • (ArgumentError)


25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/liquid_loader/liquid_validations.rb', line 25

def validates_presence_of_liquid_variable(*attr_names)
  configuration = { :message => I18n.translate('activerecord.errors.messages')[:invalid], :on => :save, :variable => nil, :container => nil }
  configuration.update(attr_names.extract_options!)

  raise(ArgumentError, "You must supply a variable to check for") if configuration[:variable].blank?
  
  validates_each(attr_names, configuration) do |record, attr_name, value|
    
    value         = value.to_s
    
    variable      = configuration[:variable].to_s
    variable_re   = /\{\{\s*#{ variable }( .*)?\}\}/

    container     = configuration[:container].to_s
    container_re  = /<\s*#{ container }.*>.*#{ variable_re }.*<\/\s*#{ container }\s*>/im

    if container.blank? && !(value =~ variable_re)
      
      record.errors.add_to_base("You must include {{ #{ variable } }} in your #{ friendly_attr_name(attr_name) }") 
    
    elsif !container.blank? && !(value =~ container_re)
    
      record.errors.add_to_base("You must include {{ #{ variable } }} inside the <#{ container }> tag of your #{ friendly_attr_name(attr_name) }")
    
    end   
  end
end