How to chain try() and scoped to_s() in Rails?

ruby-on-rails

Solution

From the fine manual:

try(*a, &b) [...] `try` also accepts arguments and/or a block, for the method it is trying

Person.try(:find, 1)

So I think you want:

@model.try(:date).try(:to_s, :long)

This one won't work:

@model.try(:date).try(:to_s(:long))

because you're trying to access the `:to_s` symbol as a method (`:to_s(:long)`). This one won't work:

@model.try(:date).try(:to_s).try(:long)

because you're trying to call the `long` method on what `to_s` returns and you probably don't have a `String#long` method defined.

Problem

In a Rails view, one can use `try` to output only if there is a value in the database, e.g ``` @model.try(:date) ``` And one can chain trys if, for example, the output is needed as a string ``` @model.try(:date).try(:to_s) ``` But what if I need to call a scoped format? I've tried ``` @model.try(:date).try(:to_s(:long)) @model.try(:date).try(:to_s).try(:long) ``` What is the correct syntax for this? And what is a good reference for more explanation? Thanks

Original source