Sha256: f3e25ecad8a4b5a8dabe56751fa7c95542b3ba7b5304494974f20516171e9dce

Contents?: true

Size: 980 Bytes

Versions: 2

Compression:

Stored size: 980 Bytes

Contents

class Redirect < ActiveRecord::Base
  belongs_to :contents, optional: true
  belongs_to :blog

  validates :from_path, uniqueness: true
  validates :to_path, presence: true
  validates :blog, presence: true

  def full_to_path
    path = to_path
    return path if path =~ /^(https?):\/\/([^\/]*)(.*)/
    url_root = blog.root_path
    path = File.join(url_root, path) unless url_root.nil? || path[0, url_root.length] == url_root
    path
  end

  def shorten
    if (temp_token = random_token) && self.class.find_by(from_path: temp_token).nil?
      temp_token
    else
      shorten
    end
  end

  def to_url
    raise 'Use #from_url'
  end

  def from_url
    File.join(blog.shortener_url, from_path)
  end

  private

  def random_token
    characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890'
    temp_token = ''
    srand
    6.times do
      pos = rand(characters.length)
      temp_token += characters[pos..pos]
    end
    temp_token
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
publify_core-9.0.0.pre6 app/models/redirect.rb
publify_core-9.0.0.pre5 app/models/redirect.rb