ruby-on-railstrailblazerrepresentable

Trailblazer Representable Change Property Name with Variable


I would like to pass in a string variable that will be used as the property name.

For example, if I have the variable property_name, which contains a string, I want to do something like this:

property :property_name, type: String, getter: ->(_) { "sample text" }

and the property name would change depending on what text I have inside the variable.

Is something like this possible? If so, what is the syntax for doing so?

Thanks for any help!


Solution

  • I have found the easiest way to accomplish this is by using the :if option.

    For example:

    property :name1, type: String, if: ->(_) { property_name == 'name1' }, getter: (_) { "sample text" }
    property :name2, type: String, if: ->(_) { property_name == 'name2' }, getter: (_) { "sample text" }
    

    The above would allow me to pass in a variable property_name. If I set the value of property_name to "name1" then the first property statement will be rendered. If I set property_name to "name2", then the second property statement will be rendered instead.