Class: CssValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/css_validator.rb

Constant Summary collapse

VENDOR_DIR =
File.join(File.expand_path('../..', __FILE__), 'vendor')

Instance Method Summary collapse

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/css_validator.rb', line 8

def validate_each(record, attribute, value)
  node_path = `which node`.rstrip
  raise 'You do not have a Node.js installed, but it is required.' unless node_path && !node_path.empty?

  return if options[:allow_nil] && value.nil?
  return if options[:allow_blank] && value.blank?

  css_file = Tempfile.new(['css', '.css'])
  css_file.write(value)
  css_file.close

  cmd = "#{node_path} #{VENDOR_DIR}/cli.js #{css_file.path}"
  Open3.popen3(cmd) do |stdin, stdout, stderr|
    result = stdout.read
    if result =~ /error/
      record.errors.add attribute, (options[:message] || 'is invalid')
    end
  end

ensure
  css_file.unlink if css_file   # deletes the temp file
end