class Eco::API::UseCases::OozeSamples::OozeRunBaseCase < Eco::API::Common::Loaders::UseCase name "ooze-run-base" type :other attr_reader :session, :options, :usecase SAVE_PATCH = "ooze_patch_update.json" def main(session, options, usecase) raise "You need to inherit from this class and call super with a block" unless block_given? @session = session; @options = options; @usecase = usecase yield end_script! end private def end_script! exit_if_no_changes! backup_patch! launch_request unless options[:simulate] exit(0) end def ooze_id options.dig(:source, :ooze_id) end def stage_id options.dig(:source, :stage_id) end def target @target ||= ooze end def new_target(object) if @target && patch_doc["page"] logger.warn "You you are switching to a new target #{object_reference(object)} after doing unsaved changes to #{object_reference(@target)}" end @target = object end def stage(id_name = stage_id) if stg = ooze.stages[id_name] || ooze.stages.get_by_name(id_name) return apiv2.pages.get(ooze_id, stage_id: stg.id).tap do |stage| if stage new_target(stage) logger.info("Got #{object_reference(stage)} from #{object_reference(ooze)}") else logger.error("Could not get stage '#{id_name}' in ooze '#{ooze_id}'") exit(1) end end end raise "Stage '#{id_name}' doesn't exist in ooze '#{ooze_id}'" end def ooze @ooze ||= apiv2.pages.get(ooze_id, stage_id: stage_id).tap do |ooze| if ooze new_target(ooze) logger.info("Got #{object_reference(ooze)}") else logger.error("Could not get ooze '#{ooze_id}'") exit(1) end end end def launch_request prompt_to_confirm! apiv2.pages.update(target).tap do |response| if response.success? logger.info("All went OK") else logger.error(response.body) end end end def exit_if_no_changes! unless changes = !!patch_doc["page"] logger.warn "No Changes!!" exit(0) end end def apiv2 @apiv2 ||= session.api(version: :oozes) end def patch_doc apiv2.pages.get_body(target) end def backup_patch! # store the request File.open(SAVE_PATCH, "w") do |file| #file << (patch_doc || {}).to_json file << JSON.pretty_generate(patch_doc || {}) end puts "Saved patch at: #{File.expand_path(SAVE_PATCH)}" end def object_reference(obj) return "No reference" unless obj "".tap do |ref| case obj when Ecoportal::API::V2::Page::Stage ref << "Stage " when Ecoportal::API::V2::Pages::PageStage ref << "StagePage " when Ecoportal::API::V2::Page ref << "Page " end ref << "'#{obj.name}' " if obj.respond_to?(:name) end end def prompt_to_confirm! micro.prompt_user("Do you want to proceed (y/N)?", default: "Y") do |response| exit(1) unless response.upcase.start_with?("Y") end end def logger session.logger end end