module ApplicationHelper
  def transactional_save(objects, skip_validations = false)
    if objects.map(&:valid?).all?
      with_transaction do
        objects.each(&:save!)
      end
    elsif skip_validations
      with_transaction do
        objects.each(&:save)
      end
    else
      false
    end
  end

  def transactional_destroy(objects)
    with_transaction do
      objects.each(&:destroy!)
    end
  end

  def multi_errors(objects)
    errors = {}
    objects.each do |object|
      object.errors.messages.each do |key, value|
        errors[key] = value
      end
    end
    errors
  end

  def encode_strings_to_utf8(attributes)
    attributes.map { |v| encode_string_to_utf8(v) }
  end

  def encode_string_to_utf8(value)
    value.encode('iso-8859-1', 'utf-8').force_encoding('utf-8')
  rescue
    value
  end

  private
    def with_transaction
      ActiveRecord::Base.transaction { yield }
      true
    rescue
      false
    end
end
