Sto cercando di aggiornare un insieme di post in uno script in Rails. Sembra esserci un comportamento strano di tipo off-by-one, dove un post viene aggiornato con il valore del post precedente.
Ho spostato tutti questi aggiornamenti per eseguire direttamente un post.raw.gsub() per “risolvere” questo problema per i post all’interno del ciclo interno (che in precedenza prendevano il valore dal post del topic), ma ora il post del topic del topic N viene aggiornato con il raw dell’ultimo post precedente del topic N-1.
Sono ancora più confuso, poiché il primo post (cioè il post del topic) viene aggiornato con tpost.raw.gsub! con il valore di post.raw.gsub!(preg,"#{$2}") dall’iterazione precedente.
MODIFICA: Bene, non sono mai riuscito a capire cosa non andava nella versione precedente, ma ecco una versione di uno script di aggiornamento di alcuni post che crea una revisione:
def fix_slack_posts
opts = { bypass_rate_limiter: true, bypass_bump: true, skip_validations: true }
reg=/(\*\*)(This topic was automatically generated from Slack. You can find the original thread \[here\].+?\))(\*\*\.)?\s*?([a-zA-Z, ()]* : )(.*)/m
preg = /([a-zA-Z, ()]+? : )(.*)/m
topic_posts = Post.where("raw like '**This topic was automatically%'")
#topic_posts = Post.where(topic_id: [23934, 23935], post_number: 1)
topic_posts.each do |tpost|
begin
puts "Fixing topic post #{tpost.id} with #{tpost.raw[0..30]}"
puts tpost.raw.gsub(reg,"1 #{$1}\n2 #{$2}\n3 #{$3}\n4 #{$4}\n 5 #{$5}")
raw = tpost.raw.gsub(reg,"#{$5}\n\n#{$2}.")
puts "Fixing topic post #{tpost.id} with #{tpost.raw[0..30]}\n---\u003e#{raw}"
user = User.find(tpost.user_id)
if raw.length \u003e 10
tpost.revise(user,{raw: raw,edit_reason: 'fix slack link location'}, opts)
end
rescue
puts "Can't update topic post #{tpost.raw}"
end
posts = Post.where(topic_id: tpost.topic_id).where("post_number \u003e 1")
posts.each do |post|
if post.raw.gsub(preg,"#{$2}").length\u003e=10
begin
puts "Fixing post #{post.id} with #{post.raw[0..30]}"
raw = post.raw.gsub(preg,"#{$2}")
user = User.find(post.user_id)
post.revise(user,{raw: raw,edit_reason: 'remove user name from text'}, opts)
rescue
puts "#{post.id}--cannot save #{post.raw}. "
end
end
end
end
end