From 5f144af2349a9cab5ed3a526bfaa23c98ea523d6 Mon Sep 17 00:00:00 2001 From: aeris Date: Tue, 11 Apr 2017 13:09:03 +0200 Subject: [PATCH] Deeply OpenStruct for better views --- app/controllers/check_controller.rb | 27 +++++++++++++++++---------- config/initializers/fixture.rb | 14 ++++++++++++++ 2 files changed, 31 insertions(+), 10 deletions(-) create mode 100644 config/initializers/fixture.rb diff --git a/app/controllers/check_controller.rb b/app/controllers/check_controller.rb index 35cca1f..ce8f6c4 100644 --- a/app/controllers/check_controller.rb +++ b/app/controllers/check_controller.rb @@ -7,23 +7,28 @@ class CheckController < ApplicationController @host = SimpleIDN.to_unicode @host respond_to do |format| format.html do - return render :processing if @result.pending + return render :processing if @result[:pending] + @result = OpenStruct.deep @result end format.json do render json: case - when @result.pending then :pending - else @result - end + when @result[:pending] then + :pending + else + JSON.pretty_generate @result + end end end end def refresh unless @result.pending - refresh_allowed = @result.date + Rails.configuration.refresh_delay - if Time.now < refresh_allowed - flash[:warning] = "Merci d’attendre au moins #{l refresh_allowed} pour rafraîchir" - return redirect_to action: :show, id: @host + if Rails.env == 'production' + refresh_allowed = @result.date + Rails.configuration.refresh_delay + if Time.now < refresh_allowed + flash[:warning] = "Merci d’attendre au moins #{l refresh_allowed} pour rafraîchir" + return redirect_to action: :show, id: @host + end end enqueue_host end @@ -31,10 +36,11 @@ class CheckController < ApplicationController end protected + def enqueue_host Datastore.pending self.type, @host, @port self.worker.perform_async *(@port.blank? ? [@host] : [@host, @port]) - @result = OpenStruct.new pending: true , date: Time.now + @result = OpenStruct.new pending: true, date: Time.now end def check_host @@ -47,11 +53,12 @@ class CheckController < ApplicationController @host, @port = @id.split ':' @host = SimpleIDN.to_ascii @host.downcase - if /[^a-zA-Z0-9.-]/.match @host + if /[^a-zA-Z0-9.-]/ =~ @host flash[:danger] = "Hôte #{@host} invalide" redirect_to action: :index return false end + @port = @port.to_i if @port @result = Datastore.host self.type, @host, @port end end diff --git a/config/initializers/fixture.rb b/config/initializers/fixture.rb new file mode 100644 index 0000000..f806300 --- /dev/null +++ b/config/initializers/fixture.rb @@ -0,0 +1,14 @@ +require 'ostruct' + +class OpenStruct + def self.deep(value) + case value + when Hash + self.new value.collect { |k, v| [k, self.deep(v)] }.to_h + when Enumerable + value.collect { |v| self.deep v } + else + value + end + end +end