以ä¸ã®ãããªå¦çãããããname ã¨ããååã®ã¦ã¼ã¶ãæ¢ãããã®å¹´é½¢ãåºåããã
def age(name) Persion.where(:name => name).age end
ä¸ã®ã³ã¼ãã¯ã¾ããã¨ãããä¸ç®æããã name ã¨ããã¦ã¼ã¶ãããªãã£ãå ´åã«ãä¾å¤ã«ãªãã¨ããç¹ã ã
def age(name) Persion.where(:name => name).age # => NilClass#age is not defined end
ãããåé¿ããããã«ã¯ãnilãã§ãã¯ãå ¥ããå¿ è¦ãããããã name ã¨ããã¦ã¼ã¶ãããªãã£ãããnilãè¿ããã¨ã«ããã
def age(name) person = Persion.where(:name => name) person ? person.age : nil end
åã«å¹´é½¢ãåå¾ãããã ããªã®ã«ãä¸éå¤æ° person ãç¨æããªãã¨ãããªãããã£ã¨ç°¡æ½ã«æ¸ããªãã ãããï¼
ActiveSupport ã® Object#presence
ã¨ããã§ãActiveSupportã«ã¯Object#presenceã¨ããã®ããããä¸èº«ã¯ããã ã
class Object def presence self if present? end end
ãã£ã¨åãããããæ¸ããªããã¨ãããã ã
class Object def presence return present? ? self : nil end end
present? ã¨ããã®ã¯ blank? ã®çå½ãéã«ããã¡ã½ãããã¤ã¾ãã空æåã空é
åãnilãfalseãªã©ã®ã¨ãã«falseãè¿ãããã以å¤ã¯trueãè¿ãã
ãã®Object#presenceã¯ä½ã«ä½¿ãã®ãã¨ããã¨ã
state = params[:state] if params[:state].present? country = params[:country] if params[:country].present? region = state || country || 'US'
ã¨æ¸ããããªã¨ããã
region = params[:state].presence || params[:country].presence || 'US'
ã¨ã·ã³ãã«ã«æ¸ããããã«ãªãã
ãããã¯å¼æ°ä»ãã®Object#presenceãä½ã
æ¬é¡ã«æ»ãã以ä¸ã®è¨è¿°ãã·ã³ãã«ã«ãããã¨ããåé¡ã
def age(name) person = Persion.where(:name => name) person ? person.age : nil end
ãããã次ã®ããã«æ¸ãã¨ããã®ãèããã
def age(name) Persion.where(:name => name).presence(&:age) end
åãããããæ¸ãç´ãã¨ããã
def age(name) Persion.where(:name => name).presence {|person| person.age} end
ã©ãããä»çµã¿ãã¨ããã¨ãObject#presenceããããã¯å¼æ°ãåãåããããã«æ¡å¼µããã
require 'active_support/core_ext/object/blank' class Object alias _orig_presence presence def presence present? ? (block_given? ? yield(self) : self) : nil end end
ãããããã¯å¼æ°ãããã°ãpresent?ãªã¨ãã«yield(self)ãè¿ãããããã¯å¼æ°ããªããã°æ¬æ¥ã®presenceã®åä½ãããã
ã¡ãã£ã¨ããããããã©ããã®æ¡å¼µãå°å
¥ãããã¨ã§ã¹ãããªæ¸ããã·ã¼ã³ãã¡ããã¡ãããã£ã¦æ°åè¯ããªãã¾ããã