kirqe
kirqe

Reputation: 2470

How to change resource in resource_url depending on Model from where it was called?

I have the following code:

  def perform(message, slug)
    url = Bitly.client.shorten(post_url(slug)).short_url
    tweet("#{message} #{url}")
  end

Lets say I also have a Book model(the code above is for Post model). And if I want to get a book url I use the following helper book_url(slug)

How can change post_url to book_url depending on model where perform was called?

So, if the method was called from Book model, I have book_path if from Post model, I have post_path.

Upvotes: 0

Views: 94

Answers (2)

dpaluy
dpaluy

Reputation: 3705

If you use Rails standard routes, like: resources :books you can do the following:

def perform(message, resource)
  url = Bitly.client.shorten(url_for(resource)).short_url
  tweet("#{message} #{url}")
end

For more info, read about url_for

Upvotes: 1

Tim Kretschmer
Tim Kretschmer

Reputation: 2280

you can dynamically call those helpers or modelfunctions with the send() method. That method is coming from Ruby, here is more info. http://apidock.com/ruby/Object/send

In your case you just do it like this:

model_name = object.class.to_s.underscore
send("#{model_name}_path", slug)

edit as for your code it might be

send("#{model_name}_url", slug, host: ActionMailer::Base.default_url_options[:host] )

i tried it for you in my console:

include Rails.application.routes.url_helpers
model_name = User.first.class.to_s.underscore
=> "user"
send("#{model_name}_path", User.first.cached_slug)
=> "/community/user/hummel"
send("#{model_name}_path", User.first.id)
=> "/community/user/1"

as on request

as you want to send a host to that method use the _url instead of _path helper and also give the extra param host into the method.

send("#{model_name}_url", User.first.cached_slug, host: "google.com")
=>http://google.com/community/user/hummel

Upvotes: 1

Related Questions