Class: Kscript::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/kscript/base.rb

Overview

Base class for all kscript scripts

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(**opts) ⇒ Base

Returns a new instance of Base.



10
11
12
13
14
15
16
# File 'lib/kscript/base.rb', line 10

def initialize(**opts)
  service = opts.delete(:service) || self.class.name
  log_level = opts.delete(:log_level) || ENV['KSCRIPT_LOG_LEVEL'] || :info
  @logger = Kscript::Logger.new(service: service, level: log_level)
  @logger.set_human_output(human_output?)
  # 其余 opts 可由子类使用
end

Instance Attribute Details

#loggerObject (readonly)

Returns the value of attribute logger.



8
9
10
# File 'lib/kscript/base.rb', line 8

def logger
  @logger
end

Class Method Details

.inherited(subclass) ⇒ Object

自动注册所有 Kscript::Base 的子类为插件



27
28
29
30
31
32
33
34
35
36
# File 'lib/kscript/base.rb', line 27

def self.inherited(subclass)
  name = subclass.name.split('::').last
  if name.start_with?('Kk') && name.end_with?('Utils')
    cmd = name[2..-6] # 去掉 Kk 和 Utils
    # 转 snake_case
    cmd = cmd.gsub(/([A-Z])/, '_\1').downcase.sub(/^_/, '').sub(/_$/, '')
    Kscript::Plugin.register(cmd.to_sym, subclass)
  end
  super if defined?(super)
end

Instance Method Details

#human_output?Boolean

判断是否为人性化输出模式(无 –log/–log-level 参数且 ENV 未设置)

Returns:

  • (Boolean)


39
40
41
# File 'lib/kscript/base.rb', line 39

def human_output?
  !(ARGV.include?('--log') || ARGV.include?('--log-level') || ENV.fetch('LOG', nil))
end

#with_error_handlingObject

通用工具方法可在此扩展



19
20
21
22
23
24
# File 'lib/kscript/base.rb', line 19

def with_error_handling
  yield
rescue StandardError => e
  logger.error("Unhandled error: #{e.class} - #{e.message}", error: e.class.name, backtrace: e.backtrace&.first(5))
  exit(1)
end