Reputation: 2470
I have a simple posing app. How can I get a post url from it's model and pass it to Bitly shortener? (replace http://www.google.com with post url)
It's probably something like
Rails.application.routes.url_helpers.posts_path(self...)
-
class TwitterWorker
include Sidekiq::Worker
def perform(title, url)
tweet("#{title} #{url}")
end
end
-
class Post < ActiveRecord::Base
include Tweets
extend FriendlyId
after_create :post_to_twitter
.....
private
def post_to_twitter
title = self.title[0..120]
url = Bitly.client.shorten("http://www.google.com").short_url
TwitterWorker.perform_async(title, url)
end
end
-
I used to have this code in model
# tweet("#{title[0..120]} #{ Bitly.client.shorten('http://www.google.com').short_url}")
UP I ended up doing the following.
Since I have a few models that can make postings, I slightly refactored post_to_tweeter meth
worker
class TwitterWorker
include Sidekiq::Worker
include Tweets
include Rails.application.routes.url_helpers
def perform(message, slug)
url = Bitly.client.shorten(post_url(slug, host: ActionMailer::Base.default_url_options[:host])).short_url
tweet("#{message} #{url}")
end
end
model
after_create :post_to_twitter
def post_to_twitter
message = "#{self.title[0..120]}"
TwitterWorker.perform_async(message, self.slug)
end
Upvotes: 0
Views: 2576
Reputation:
If you're using the model IDs in the URL, you can use the code below. However, I like to use the obfuscate_id and/or friendly_id gems to prevent users from knowing how many records are in the database.
Model:
class Post < ActiveRecord::Base
...
private
def post_to_twitter
title = self.title[0..120]
TwitterWorker.perform_async(title, self.id)
end
end
Twitter Worker:
class TwitterWorker
include Sidekiq::Worker
def perform(title, post_id)
tweet("#{title} Bitly.client.shorten(post_url(#{post_id})).short_url)
end
end
This will set the url to http://localhost.com/post/123 if 123 is the post id.
To set what your website is in staging and production enviroments, here's a quick read - How does rails 4 generate _url and _path helpers.
P.S. You can also use the post_url trick for including the absolute URLS in emails.
Upvotes: 1
Reputation: 3330
you can include the url helpers in models (though it normally is not the best way of dealing with things)
class MyClass < ActiveRecord::Base
include Rails.application.routes. url_helpers
end
Upvotes: 2