gpt4 book ai didi

ruby-on-rails - 使用服务类中的计算属性构建哈希

转载 作者:行者123 更新时间:2023-12-04 03:36:54 25 4
gpt4 key购买 nike

我想帮忙完成一段代码。我不知道如何解释我需要什么,所以我会一点一点地告诉你。

我有这个模型:

class Metric < ApplicationRecord
belongs_to: :post
after_save: :analysis!

# The table Metrics has the following columns:
# adverb_count
# adverb_density
# sentiment
# word_count
# letter_count

def analysis!
res = MetricService.call post.body
update! res
end
end

保存度量实例后,我需要调用一个外部服务,该服务将返回一个哈希值,其中包含可帮助我计算值的属性adverb_countadverb_densitysentimentword_count,最后是 letter_count。为此,我创建了一个封装此逻辑的 MetricService 类:

class ApplicationService
def self.call(*args, &block)
new(*args, &block).call
end
end

class MetricService < ApplicationService
extend Memoist

def initiaze(text)
@text = text
end

# TODO: return the
def call
pre_analysis
# =>
# Hash containing several props

post_nalysis
# =>
# Hash containing sereral props
end

private

def pre_analysis
client.pre_analysis @text
end
memoize :pre_analysis

def post_analysis
client.post_analysis pre_analysis['id']
end

def client
SDK::Service.new ENV['API_KEY']
end
memoize :client
end

在这个类实例化之后,我调用了client的两个方法:pre_analysispost_analyis,通过这两个信息我可以最后计算属性 adverb_count、adverb_density、sentiment、word_count 和 letter_count 的值并将其返回给 Metric。我想做的是为每个属性创建一个方法:

class MetricService < ApplicationService

# ...
def adverb_count
# use pre_analysis and post_analysis to computate this value here
end

def adverb_density
# use pre_analysis and post_analysis to computate this value here
end

def sentiment
# use pre_analysis and post_analysis to computate this value here
end

def word_count
# use pre_analysis and post_analysis to computate this value here
end

def letter_count
# use pre_analysis and post_analysis to computate this value here
end
# ...
end

call 方法中,我只是调用它们并返回哈希值。

根据我的研究,ROR 上的服务应该只包含一个公共(public)方法,所以我想我应该将这些属性保密。这是一个正确的假设吗?

有没有一种方法可以从 #call 构建散列,而不必单独调用这些方法中的每一个?例如:

def call
{
adverb_count: adverb_count
# etc
}
end

谢谢。

最佳答案

您可以像这样使用元编程:

# the only public method
def call
%w[adverb_count adverb_density sentiment word_count letter_count].each_with_object({}) do |method_name, result|
result[method_name] = send(method_name)
end
end

private

def adverb_count
# use pre_analysis and post_analysis to computate this value here
end

def adverb_density
# use pre_analysis and post_analysis to computate this value here
end

# and so on...

关于ruby-on-rails - 使用服务类中的计算属性构建哈希,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58612857/

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