iT邦幫忙

2021 iThome 鐵人賽

DAY 3
0
自我挑戰組

Ruby on Rails 與它們相關的東西 II系列 第 3

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/

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


上一篇
Day02 - 修改 Rails console edit 編輯模式
下一篇
Day04 - Gem-activerecord-import 批次建立介紹與應用
系列文
Ruby on Rails 與它們相關的東西 II30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
MaxHarry
iT邦新手 4 級 ‧ 2021-09-16 21:28:24

product = Shop.new

怪怪的

祝福順利完賽

小菜 iT邦新手 3 級 ‧ 2021-09-16 23:45:53 檢舉

寫到太累沒注意到
謝謝提醒!!!

我要留言

立即登入留言