What is the point of object.presence?

后端 未结 5 924
太阳男子
太阳男子 2021-02-06 20:33

In the Rails docs, the example provided for the object.presence method is:

region = params[:state].presence || params[:country].presence || \'US\'
<         


        
5条回答
  •  日久生厌
    2021-02-06 20:46

    The real point of using #presence is that it expands the notion of falsey values to handle web and http scenarios. The docs don't make this purpose clear ... instead simply focussing on the method's API: The what but not the why. Web and HTTP is different from normal programming because a blank string is often what you get instead of a nil from a request.

    In plain Ruby, however, an empty string is truthy. This makes web developers write a lot of redundant boilerplate code like the docs for Object.presence uses as its example, as others here have quoted.

    The bottom line for people writing web applications in Rails is that we can (should) now use #present? and #presence with the standard Ruby short-circuiting or, ||:

    # Check for a param like this
    @name = params[:name].presence || 'No name given'
    

    That line properly handles everything the web server packs into the request params for us. While this plain old ruby does not:

    # DON'T DO THIS
    @name = params[:name] || 'No name given'
    

提交回复
热议问题