あなたの例のコードは、RailsのDSLの一部です。あなたが実際に設定しているのはちょうどコードのように見えるハッシュです。
内部的に、Railsはbefore_save
コールの条件を指定するこのハッシュを評価します。非常に単純化されたバージョンで
、保存時にRailsは基本的にこれを行います:
再び
class ActiveRecord::Base
@before_save_rules = []
def self.before_save(method, options={})
@before_save_rules << [method, options]
end
def self.before_save_rules
@before_save_rules
end
def save
# Evaluate the defined rules and decide if we should perform the
# before_save action or not
self.class.before_safe_rules.each do |method, options|
do_perform = true
if options.key?(:if)
do_perform = false unless send(options[:if])
end
if options.key?(:unless)
do_perform = false if send(options[:unless])
end
send(method) if do_perform
end
# now perform the actual save to the database
# ...
end
end
、これは非常に単純化され、ちょうど実際のコードの精神であるが、これはそれがどのように動作するか基本的にあります。
このバグが数か月前に報告されたことを知りました:[Bug#12177:* irbコンソールの新しいハッシュ構文を持つハッシュのシンボルとして 'if:'を使用する*](https://bugs.ruby -lang.org/issues/12177) –