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/

備註:之後文章修改更新,以個人部落格為主

--

--

被端走的小菜
被端走的小菜

Written by 被端走的小菜

大家好,我是被端走的小菜。以個人部落格更新為主:https://riverye.com/

No responses yet