【发布时间】:2015-07-18 19:08:29
【问题描述】:
我有一个简单的姿势应用程序。如何从其模型中获取帖子网址并将其传递给 Bitly 缩短器? (将http://www.google.com替换为帖子网址)
大概是这样的
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
-
我曾经在模型中有这段代码
# tweet("#{title[0..120]} #{ Bitly.client.shorten('http://www.google.com').short_url}")
向上 我最终做了以下事情。
由于我有几个模型可以发帖,所以我稍微重构了 post_to_tweeter 方法
工人
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
型号
after_create :post_to_twitter
def post_to_twitter
message = "#{self.title[0..120]}"
TwitterWorker.perform_async(message, self.slug)
end
【问题讨论】:
-
模型不应该知道任何关于 url 的事情。将您的方法移到其他地方,例如帮助器。
标签: ruby-on-rails ruby