【问题标题】:How to make a strip in a response in ruby/rails?如何在 ruby​​/rails 中做出响应?
【发布时间】:2021-06-21 17:47:16
【问题描述】:

我正在努力弥补一些东西,就是当推送通知到达设备时,如果用户定义的标题末尾有空格,则该空格出现在推送通知中。它看起来很丑陋,我一直在努力得到它。我知道我可以用 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

【问题讨论】:

    标签: ruby-on-rails json ruby api backend


    【解决方案1】:

    使用String#strip

    返回带有前导和尾随空格的接收器副本 删除。

    空白被定义为以下任何字符:null, 水平制表符、换行符、垂直制表符、换页、回车、 空间。

     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
    

    如果您只想删除尾随空格,请改用String#rstrip

    ActiveSupport 还具有squish 方法,该方法将连续的空白组替换为一个空格并剥离字符串。

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

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

    【讨论】:

    • 我应用了你所说的,效果非常好。但是它仍然在几个地方抛出了同样的错误,所以我最终使用了 StripAttributes Gem 来解决它,现在我们可以解决这个问题了。所以,干杯人,非常感谢!
    猜你喜欢
    • 2016-01-24
    • 2021-01-01
    • 2020-12-22
    • 1970-01-01
    • 2012-11-20
    • 1970-01-01
    • 2021-03-05
    • 1970-01-01
    • 2011-09-14
    相关资源
    最近更新 更多