Module: URLAttributes::ActiveRecord

Defined in:
lib/url_attributes/extensions/active_record.rb

Instance Method Summary collapse

Instance Method Details

#url_attribute(attribute_name, before: :save) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/url_attributes/extensions/active_record.rb', line 16

def url_attribute(attribute_name, before: :save)
  validates attribute_name, :url => true, :if => "#{attribute_name}.present?"

  callback_method = :"before_#{before}"
    
  # Add "http://" to the URL if it's not already there.
  send(callback_method) do |record|
    url = record[attribute_name]
    if url.present? && !(url =~ /\A\s*https?:\/\//)
      url = "http://#{url.try(:strip)}"
    end
    record[attribute_name] = url
  end

end