【发布时间】:2014-10-02 08:50:10
【问题描述】:
我试图找出在验证期间是否可以执行一个方法调用来更改进入数据库的某些属性的信息。所需的工作流程是:用户提交一个 url,我对其进行验证,如果它与正则表达式匹配,则调用 embedly。 embedly 函数获取 title 和 image_url 的信息。我也想对 title 和 image_url 执行验证,但是在我调用 embedly 方法之前这些都不存在。
有没有办法: 1.验证link_url 2.调用embedly方法 3.验证生成的title和image_url属性?
感谢任何帮助:
class ListLink < ActiveRecord::Base
belongs_to :list
default_scope -> {order('created_at DESC')}
#the REGEX urls are matched against
VALID_URL_REGEX = /\A(http:\/\/|https:\/\/|www|)[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(([0-9]{1,5})?\/.*)?\z/i
validates :link_url, presence: true,
format:{with: VALID_URL_REGEX, message: "Please enter a valid url."}
validates :list_id, presence: true
#if is a valid url, ping embedly for more information on it
before_save :embedly
#is it possible to call just these 2 validations after the :embedly method?
validates :title, presence: true, length:{minimum: 4, maximum: 200}
validates :image_url, presence: true
private
def embedly
embedly_api = Embedly::API.new :key => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
:user_agent => 'Mozilla/5.0 (compatible; mytestapp/1.0; my@email.com)'
#duplicate the url for use in the embedly API
url = link_url.dup
obj = embedly_api.extract :url => url
#extract and save a title and image element to the database
self.title = obj[0].title
self.image_url = obj[0]["images"][0]["url"]
end
end
【问题讨论】:
-
我不这么认为 - 我认为您必须检查 embedly 方法中 url 的格式
标签: ruby-on-rails ruby regex validation