user3442206
user3442206

Reputation: 587

Construct strings in ruby

I have a model called Book and another one called Magazine.

They share the same index view, where pictures of the covers are shown.They are also displayed according to their appearance date, so instances of those two models are mixed in the view...

Each cover has a clickable tite, and leads the user to a description page for this particular book or magazine...

Now in my view,i want to be able to do something like :

<%= link_to document.title, "#{document.class.name.underscore}"_path(document) %>

So in the case of book, i want this line to be replaced by the path from book_path(document) when document is a book,and by the path generated by magazine_path(document) when the document is a magazine.

À la bash script syntax...

How would i realize this.

Thank you very much!

Upvotes: 1

Views: 58

Answers (2)

BroiSatse
BroiSatse

Reputation: 44715

Try:

<%= link_to document.title, polymorphic_path(document) %>

Polymorphic path, when executed with a model, checks the class of passed model, brings it do underscored notation and executes model_name_path. Seems to be exactly what you need.

Upvotes: 3

Tiago Farias
Tiago Farias

Reputation: 3407

You can always do this with eval.

<%= link_to "Title", eval("#{document.class.name.underscore}_path(document)") %>

There is also send, which is cleaner, but also metaprogramming:

<%= link_to "Title", send("#{document.class.name.underscore}_path", document) %>

Upvotes: 0

Related Questions