如何在 ruby/rails 中的响应中制作条带?

How to make a strip in a response in ruby/rails?

我正在努力编一些东西,就是当推送通知到达设备时,如果用户定义的标题最后有一个空白space,空白space 出现在推送通知中。它看起来很丑,我一直在努力得到它。我知道我可以用 rstrip 做到这一点,但不确定如何或在哪里。有人可以帮我吗?干杯!

这是其中一种方法:

 def self.sell_alert(user, amount, poi_picture)
    return if user.device_token.nil?
    create_params = {
      date: DateTime.now,
      title: "Your content has been sold!",
      message: "\"#{poi_picture.title #Here lies the problem#}\" was sold for $#{sprintf('%.2f',amount)} and your account has been credited. Cheers!",
      poi_picture_id: poi_picture.id,
      notification_type: :payment
    }
    create_and_send_notification(create_params, user.id, SellAlertWorker)
  end

使用String#strip

Returns a copy of the receiver with leading and trailing whitespace removed.

Whitespace is defined as any of the following characters: null, horizontal tab, line feed, vertical tab, form feed, carriage return, space.

 def self.sell_alert(user, amount, poi_picture)
    return if user.device_token.nil?
    create_params = {
      date: DateTime.now,
      title: "Your content has been sold!",
      message: "\"#{poi_picture.title.strip}\" was sold for $#{sprintf('%.2f',amount)} and your account has been credited. Cheers!",
      poi_picture_id: poi_picture.id,
      notification_type: :payment
    }
    create_and_send_notification(create_params, user.id, SellAlertWorker)
  end

如果您只想删除尾随白色space,请改用String#rstrip

ActiveSupport 还有 squish 方法,可以将连续的白色 space 组替换为一个 space 以及剥离字符串。

我可能会在 setter 中处理这个问题,而不是从根本上解决问题,而不是在输出标题的任何地方重复相同的步骤:

class PoiPicture < ApplicationRecord
  def title=(str)
    super(str.squish)
  end
end