diff --git a/app/controllers/admin/links_controller.rb b/app/controllers/admin/links_controller.rb index 07d045db..20a7d766 100644 --- a/app/controllers/admin/links_controller.rb +++ b/app/controllers/admin/links_controller.rb @@ -18,7 +18,12 @@ class Admin::LinksController < Admin::ItemsController def create @item = Link.new(params[:link]) - if @item.save + if @item.save(params[:link]) + success = true + else + success = check_valid_url + end + if success flash.now[:notice] = t('create.success.link') respond_to do |format| format.js { render 'admin/items/reload_items' } @@ -33,6 +38,11 @@ class Admin::LinksController < Admin::ItemsController @item = Link.find(params[:id]) if @item.update_attributes(params[:link]) + success = true + else + success = check_valid_url + end + if success flash.now[:notice] = t('update.success.link') respond_to do |format| format.js { render 'admin/items/reload_items' } @@ -42,5 +52,42 @@ class Admin::LinksController < Admin::ItemsController render :action => "edit" end end + + protected + + def check_valid_url + if @item.errors.include?(:url) && !@item.errors.added?(:url, :blank) && @item.errors.added?(:url, :invalid) + begin + url = @item.url + url.gsub!('http://', '').slice!(/^\//) + path = Rails.application.routes.recognize_path(url) + if path.has_key?(:page_name) + if Page.where(path: path[:page_name]).first + new_url = "#{request.base_url}/#{url}" + else + success = false + end + else + new_url = "#{request.base_url}/#{url}" + end + if @item.errors.count == 1 + @item.url = new_url + if @item.save + success = true + else + success = false + end + else + @item.url = new_url + success = false + end unless success == false + rescue + success = false + end + else + success = false + end + success + end end diff --git a/app/models/link.rb b/app/models/link.rb index d3e1448c..a7aa7cf6 100644 --- a/app/models/link.rb +++ b/app/models/link.rb @@ -2,7 +2,7 @@ class Link < Item field :url - validates :url, :presence => true, :format => /^(http|https):\/\/(([a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5})|((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))(:[0-9]{1,5})?(\/.*)?/i + validates :url, :presence => true, :format => /^(http|https):\/\/(([a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5})|((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))|localhost(:[0-9]{1,5})?(\/.*)?/i before_validation :add_http @@ -13,7 +13,7 @@ class Link < Item protected def add_http - unless self.url[/^http:\/\//] || self.url[/^https:\/\//] + unless self.url[/^(http|https):\/\//] || self.url.blank? self.url = 'http://' + self.url end end diff --git a/app/views/admin/items/_node.html.erb b/app/views/admin/items/_node.html.erb index 100dbda1..a0926f4d 100644 --- a/app/views/admin/items/_node.html.erb +++ b/app/views/admin/items/_node.html.erb @@ -11,7 +11,11 @@ <% end %>