最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Rails way to elegantly avoid Zero Width Space character problems - Stack Overflow

programmeradmin1浏览0评论

We had a Zero Width Space character problem with our rails app. Somebody copied and pasted a configuration value (a URL) into a form in our rails app, which later caused confusing error messages. It turned out to be caused by the pasted string having a leading Zero Width Space character, preventing it matching other strings as expected. Evil.

We have a large rails app with lots of form fields (ActiveAdmin), so my question is... is there an elegant/recommended way of always stripping away Zero Width Space characters, so that we never hit such an issue again? Should I try to apply such a fix across all form fields?

I'm thinking of adding a method:

  def strip_zero_width_chars
    attributes.each do |attr, value|
      if value.is_a?(String)
        self[attr] = value.strip.gsub(/[\u200B\u200C\u200D\uFEFF]/, '')
      end
    end
  end

And applying that to my config model with before_save :strip_zero_width_chars, to solve it for this particular form.

But I'm not sure if there's a better more elegant way (Side note: I was a bit surprised that ruby strip doesn't get rid of zero width spaces)

And my instinct is to stop short of making this fix apply to all models throughout the app, for fear of unintended consequences. Can anyone offer any wisdom/experience either way?

发布评论

评论列表(0)

  1. 暂无评论