gpt4 book ai didi

ruby-on-rails - 重构此 Ruby 和 Rails 代码

转载 作者:太空宇宙 更新时间:2023-11-03 18:01:01 25 4
gpt4 key购买 nike

我有这个模型:

class Event < Registration
serialize :fields, Hash
Activities=['Annonce', 'Butiksaktivitet', 'Salgskonkurrence']

CUSTOM_FIELDS=[:activity, :description, :date_from, :date_to, :budget_pieces, :budget_amount, :actual_pieces, :actual_amount]
attr_accessor *CUSTOM_FIELDS

before_save :gather_fields
after_find :distribute_fields

private

def gather_fields
self.fields={}
CUSTOM_FIELDS.each do |cf|
self.fields[cf]=eval("self.#{cf.to_s}")
end
end

def distribute_fields
unless self.fields.nil?
self.fields.each do |k,v|
eval("self.#{k.to_s}=v")
end
end
end
end

我觉得这可以做得更短、更优雅。有人有想法吗?

  • 雅各布

顺便说一句。谁能告诉我 CUSTOM_FIELDS 前面的星号是做什么用的?我知道它在方法定义 (def foo(*args)) 中做了什么,但在这里不知道...

最佳答案

好的,首先:永远不要 10000000000.times { puts "ever"} 当你不知道自己是什么时使用 eval正在做。它是 Ruby 世界的核弹,因为它可以在广阔的区域造成破坏,在您的代码中引起类似于辐射中毒的症状。只是不要。

考虑到这一点:

class Event < Registration
serialize :fields, Hash
Activities = ['Annonce', 'Butiksaktivitet', 'Salgskonkurrence']

CUSTOM_FIELDS = [:activity,
:description,
:date_from,
:date_to,
:budget_pieces,
:budget_amount,
:actual_pieces,
:actual_amount] #1
attr_accessor *CUSTOM_FIELDS #2

before_save :gather_fields
after_find :distribute_fields

private

def gather_fields
CUSTOM_FIELDS.each do |cf|
self.fields[cf] = send(cf) #3
end
end

def distribute_fields
unless self.fields.empty?
self.fields.each do |k,v|
send("#{k.to_s}=", v) #3
end
end
end
end

现在做一些笔记:

  1. 通过将每个自定义字段放在自己的行中,可以提高代码的可读性。我不想滚动到行尾来阅读所有可能的自定义字段或添加我自己的字段。
  2. 传递到 attr_accessor*CUSTOM_FIELDS 使用所谓的“splat 运算符”。通过以这种方式调用它,CUSTOM_FIELDS 数组的元素将作为单独的参数传递给 attr_accessor 方法,而不是作为一个(数组本身)
  3. 最后,我们使用send方法来调用我们在编程时不知道名称的方法,而不是邪恶的eval

除此之外,我找不到任何关于此代码的重构。

关于ruby-on-rails - 重构此 Ruby 和 Rails 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4746138/

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