Day03 - Gem-strip_attributes 介绍与应用

前言

当使用者输入资料时,若不小心输入跳脱字元 Escape Character,如 \n or \t 等时,在资料处理与储存时,应该要过滤,避免日後使用者查不到该资料 (或其它问题),进而衍伸客服 (or Bug)

方法 1

Ruby 内建 strip方法,可以用过该方法过滤

$ irb

"  hello\t"
# "  hello\t"

"  hello\t".strip
# "hello"

方法 2

使用 strip_attributes Gem,可参考此 commit

# 在想使用的 Model 中加入 (以 shop 为例)
# app/models/shop.rb
class Shop < ApplicationRecord
  strip_attributes
end

---

# 写个测试覆盖
# spec/models/shop_spec.rb
require 'rails_helper'

RSpec.describe Shop, type: :model do
  describe "#strip_attributes" do
    context "note" do
      subject do
        shop = Shop.new(name: "TEST", email: "TEST", note: "TEST\n")
        shop.valid?
        shop.note
      end

      it { is_expected.to eq("TEST") }
    end
  end
end

参考资料

  1. strip (String) - APIdock
  2. strip_attributes GitHub

铁人赛文章连结:https://ithelp.ithome.com.tw/articles/10264570
medium 文章连结:https://link.medium.com/tBNoHEh2Mjb
本文同步发布於 小菜的 Blog https://riverye.com/

备注:之後文章修改更新,以个人部落格为主


<<:  【Day 01】- 前言: 从 0 开始的网路爬虫

>>:  Day 16 - Rancher 指令工具的操作

[iT铁人赛Day5]JAVA的优先顺序

上次优先顺序还没讲,今天就来讲解一下 数学的运算符号有优先顺序的差别,JAVA也有 数学符号无疑是加...

Day 9. 双向绑定-MVVM

常提到的设计架构MVC与MVVM MVC MVC全名为Model View Controller ,...

Proxmox VE 虚拟机管理操作 (二)

虚拟机的建置与操作已经来到基本使用的程度了,对於各种应用修改与尝试後可能伴随虚拟机被搞砸的风险。 ...

18.移转 Aras PLM大小事-快速贴入ECR受影响物件

这篇一样是Excel复制了很多料号,然後贴入ECR受影响物件 左边一个输入框,右边是系统讯息,上面一...

[day 17] Swift 语法梳理後续

Swift 语法介绍 枚举(Enumerations) ,类和结构体 枚举(Enumerations...