optional local variables in rails partial templates: how do I get out of the (defined? foo) mess?

前端 未结 12 2331
没有蜡笔的小新
没有蜡笔的小新 2020-12-04 04:41

I\'ve been a bad kid and used the following syntax in my partial templates to set default values for local variables if a value wasn\'t explicitly defined in the :locals has

12条回答
  •  忘掉有多难
    2020-12-04 05:21

    Since local_assigns is a hash, you could also use fetch with the optional default_value.

    local_assigns.fetch :foo, default_value
    

    This will return default_value if foo wasn't set.

    WARNING:

    Be careful with local_assigns.fetch :foo, default_value when default_value is a method, as it will be called anyway in order to pass its result to fetch.

    If your default_value is a method, you can wrap it in a block: local_assigns.fetch(:foo) { default_value } to prevent its call when it's not needed.

提交回复
热议问题