zoukankan      html  css  js  c++  java
  • (GoRails) 如何去掉form输入框头尾的空格;何时用callbacks,gem;

    视频:https://gorails.com/episodes/when-callbacks-and-adding-dependencies-are-good?autoplay=1

    主题:应当在什么时候使用callbacks, 应当什么时候使用小的功能gem?

    根据需要灵活把握


    如何去掉Form输入框中,在header或trailing不小心输入的空格?

    1. 使用String#strip。可以去掉首尾的whitespace。

    2. 如果是User类中的email, name等fields。可以在User类中使用:

    validates :email, presence: true

    def email=(value)

      super(value.strip)

    end

    super关键字: 调用当前方法在父类中的方法。

    使用email=方法,分配的value被stripped,然后返回了原始的email=方法。

    不要用javascript实现去掉空格的功能,因为javascript可以被关掉。

    s


    需要注意,自定义的回调的适用范围

    反例:

    在Model层,User类,自定义一个callback方法:after_create :send_welcome_email

    这导致业务逻辑进入了model 回调。当业务逻辑发生变化,这个代码就不适用了。

    正例:

    在Model层,User类,自定义一个callback方法:before_validation :strip_whitespace

    def strip_whitespace

     self.email = email.to_s.strip

     self.username = username.to_s.strip

    end

    所有需要去掉空格的fields都可以放入这个方法中

    ⚠️ 核心要点:要和业务逻辑相关。


    如果有多个model需要使用strip_whitespanc则可以把这个功能做成一个类,

    然后在需要的地方:

    include StripWhitespace

    strip_whitespace :email, :username


    strip whitespace有一个小的gem 可以使用:

    https://github.com/rmm5t/strip_attributes/blob/master/lib/strip_attributes.rb

  • 相关阅读:
    CS231n笔记 Lecture 4 Introduction to Neural Networks
    CS231n笔记 Lecture 3 Loss Functions and Optimization
    CS231n笔记 Lecture 1 Introduction
    LeetCode
    Python备忘录
    Celery简介
    SaltStack error: No module named 'salt'
    IO模型
    TCP协议的三次握手和四次分手
    第一章:正则表达式
  • 原文地址:https://www.cnblogs.com/chentianwei/p/9577665.html
Copyright © 2011-2022 走看看