diff --git a/source/app/controllers/urls_controller.rb b/source/app/controllers/urls_controller.rb index ef26710..a28a5a0 100644 --- a/source/app/controllers/urls_controller.rb +++ b/source/app/controllers/urls_controller.rb @@ -1,2 +1,39 @@ class UrlsController < ApplicationController + def create + @url = Url.new(urls_params) + + if @url.save + redirect_to urls_path + else + render 'new' + end + end + + def index + @urls = Url.all + end + + def new + @url = Url.new + end + + def route_me + url = Url.find_by_short_url params[:short_url] + + if url.nil? + redirect_to root_path + else + url.update('click_count' => url.click_count + 1) + redirect_to url.long_url + end + + + end + + private + + def urls_params + params.require(:url).permit(:long_url) + end + end diff --git a/source/app/models/url.rb b/source/app/models/url.rb new file mode 100644 index 0000000..b1b2399 --- /dev/null +++ b/source/app/models/url.rb @@ -0,0 +1,34 @@ +require 'uri' +require 'net/http' + +class Url < ActiveRecord::Base + before_save :shorten_url + validates :long_url, presence: true + validate :long_url_proper_format, :long_url_responds + + private + + def shorten_url + if short_url.nil? + self.short_url = (0...7).map { [*'0'..'9', *'A'..'Z', *'a'..'z'].sample }.join + end + end + + def long_url_proper_format + unless long_url.start_with? 'http://', 'https://' + errors.add(:long_url, 'not in a valid format. (must start with http:// or https://)') + end + end + + def long_url_responds + link = URI.parse(long_url) + if link.is_a?(URI::HTTP) || link.is_a?(URI::HTTPS) + Net::HTTP.get_response(link) + else + errors.add(:long_url, 'must be reachable.') + end + rescue + errors.add(:long_url, 'must be reachable.') + end + +end diff --git a/source/app/views/layouts/application.html.erb b/source/app/views/layouts/application.html.erb index f946432..ebd783d 100644 --- a/source/app/views/layouts/application.html.erb +++ b/source/app/views/layouts/application.html.erb @@ -5,10 +5,22 @@ <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %> <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %> <%= csrf_meta_tags %> + + + + + +
-<%= yield %> +