0

I have a helper method that I want to use for several models to save having to repeat the same code several times.

def link_to_follow(instance:instance,type:type)
  link_to('Unfollow', unfollow_books_path(id: instance.id), 
          method: :post, 
          id: "unfollow_link_#{instance.id}",
          remote: true)
end

How do I do it so that if I pass type:'magazine' as a variable then unfollow_books_path becomes unfollow_magazines_path ?

amoks
  • 123
  • 9

1 Answers1

1

How about something like:

def link_to_follow(instance:instance, type:type)
  link_to(
    'Unfollow', 
    send("unfollow_#{type.pluralize}_path", instance), 
    method: :post, 
    id: "unfollow_link_#{instance.id}",
    remote: true
  )
end  

I suppose you might also be able to do:

def link_to_follow(instance:instance)
  link_to(
    'Unfollow', 
    send("unfollow_#{instance.class.name.underscore.pluralize}_path", instance), 
    method: :post, 
    id: "unfollow_link_#{instance.id}",
    remote: true
  )
end
jvillian
  • 19,953
  • 5
  • 31
  • 44