require "sibu_apidae/version" module SibuApidae class ApidaeList attr_accessor :selection_id def initialize(init_hash) @selection_id = init_hash["selection"] end def results if selection_id.blank? Apidae::Selection.first.objects.limit(2).includes(:town) else Apidae::Selection.find_by_apidae_id(selection_id).objects.includes(:town) end end end class ApidaeResult attr_accessor :obj_id def initialize(init_hash) @obj_id = init_hash["obj_id"] end def obj Apidae::Obj.find_by_apidae_id(obj_id) || Apidae::Obj.first end end class Helper APIDAE_OBJ_SOURCE = 'Fiche Apidae' def self.update_pages(site_id, obj_apidae_id = nil) conf = Rails.application.config.sibu_apidae if is_valid?(conf) apidae_pages = Sibu::Page.where(site_id: site_id).where("metadata LIKE '%\"source\":\"#{APIDAE_OBJ_SOURCE}\"%'") .select(:id, :site_id, :metadata).to_a apidae_pages = apidae_pages.select {|p| p.external_id == obj_apidae_id} unless obj_apidae_id.blank? apidae_pages.each do |p| obj = Apidae::Obj.find_by_apidae_id(p.external_id) if obj p.update(name: obj.title, title: obj.title, description: obj.short_desc, path: conf[:obj_path].call(obj)) else Rails.logger.info("Deleting page #{p.id} after object deletion (#{p.external_id})") p.destroy end end Rails.logger.info("Completed sibu pages update/delete for site #{site_id}") apidae_pages = Sibu::Page.where(site_id: site_id).where("metadata LIKE '%\"source\":\"#{APIDAE_OBJ_SOURCE}\"%'") .select(:id, :site_id, :metadata).to_a apidae_pages = apidae_pages.select {|p| p.external_id == obj_apidae_id} unless obj_apidae_id.blank? objs = obj_apidae_id.blank? ? Apidae::Obj.all : Apidae::Obj.where(apidae_id: obj_apidae_id) objs.each do |obj| if conf[:supported_types].include?(obj.apidae_type) obj_page = apidae_pages.find {|p| p.external_id == obj.apidae_id} unless obj_page p = Sibu::Page.new(name: obj.title, site_id: site_id, path: conf[:obj_path].call(obj), title: obj.title, description: obj.short_desc, source: APIDAE_OBJ_SOURCE, external_id: conf[:page_external_id].call(obj)) p.sections = conf[:obj_sections].call(obj, site_id) p.save! end end end Rails.logger.info("Completed sibu pages creation for site #{site_id}") else Rails.logger.error "Please provide a valid configuration for the sibu_apidae gem " + "(:page_external_id, :obj_path, :obj_sections and :supported_types are required)" end "SibuApidae pages update complete for site #{site_id}" end def self.is_valid?(conf) conf && conf.key?(:obj_path) && conf.key?(:obj_sections) && conf.key?(:supported_types) && conf.key?(:page_external_id) end end end