gpt4 book ai didi

ruby - 一次定义类和实例方法 - Ruby

转载 作者:太空宇宙 更新时间:2023-11-03 17:05:26 24 4
gpt4 key购买 nike

我愿意:

module MyLog

def log
unless @log
@log = Logger.new(log_path)
@log.formatter = proc do |severity, datetime, progname, msg|
"#{datetime} #{msg}\n"
end
end
@log
end

end

像这样在其他类之间重用:

Class A
def self.log_path; 'log/a.log' end
def log_path; 'log/a.log' end
include MyLog
extend MyLog

def some_method
log.debug 'some thing'
end

def self.some_class_method
log.debug 'in a class method'
end

end

有没有比A类开始的那四条线更短的路呢?

另一件事

我想批量登录:

def expire
expired_ids = []
failed_ids = []

all.each do |event|
if event.expire # saves record
expired_ids << event.id
else
failed_ids << event.id
end
end

log.debug "These ids were expired: #{ expired_ids }"
log.debug "These ids failed to expire: #{ failed_ids }"
end

有没有办法让我干净地做到这一点?将日志记录与方法逻辑分开?

最佳答案

这就是我最近在遇到像您这样的问题时一直在做的事情:

class A
class << self
include MyLog

def log_path
'log/a.log'
end
end

delegate :log_path, :log, to: "self.class"
end

否则,选择最佳编程方法取决于您的情况、您将重用脚本的频率、在其生命周期内需要重构脚本的次数等等。但无论如何,请不要试图节省代码的,尽量省去自己下次阅读代码时的麻烦。

关于你的第二个问题,你面临的主要困境是,是否值得你引入 Events 类:

class Events < Array
def foobar
each_with_object [[], []] do |event, (expired_ids, failed_ids)|
( event.expire ? expired_ids : failed_ids ) << event.id
end
end
end

然后当时间到来时:

def expire
expired_ids, failed_ids = Events[ all ].foobar
log.debug "These ids were expired: #{ expired_ids }"
log.debug "These ids failed to expire: #{ failed_ids }"
end

关于ruby - 一次定义类和实例方法 - Ruby,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18095327/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com