sutty/app/models/site/find_and_replace.rb

46 lines
1.2 KiB
Ruby
Raw Permalink Normal View History

2020-06-09 14:22:13 +00:00
# frozen_string_literal: true
class Site
# Busca y reemplaza metadatos
module FindAndReplace
# Realiza la búsqueda y reemplazo.
#
# @param [String,Symbol] :field El campo donde buscar
# @param [Any] :search El valor a buscar
# @param [Any] :replace El valor de reemplazo
def find_and_replace(field:, search:, replace:)
modified = []
field = field.to_sym
docs.each do |doc|
next unless doc.attribute? field
case doc[field].value
when Array
doc[field].value.map! do |x|
x == search ? replace : x
end
when Hash
doc[field].value.transform_values! do |x|
x == search ? replace : x
end
when NilClass
# nothing
else
doc[field].value = replace if doc[field].value == search
end
modified << doc.path.absolute if doc.save(validate: false)
end
return if modified.empty?
author = GitAuthor.new email: "sutty@#{Site.domain}", name: 'Sutty'
repository.commit(file: modified,
message: I18n.t('sites.find_and_replace'),
usuarie: author)
end
end
end