我有一个用Rails API构建的Web应用程序来收集提交。我有一个正在提交的表单,它会向具有匹配属性(位置,大小等)的某些商店发送电子邮件。它们基于以下字段进行匹配
- 位置
- 容量(最小和最大)
- 商店类型(酒店,餐饮,独特)
我也有一个属性的商店接收所有线索,我想覆盖任何前面的选项,如果设置为真。
在我的Rails API中的hard_worker.rb中,我让它检查以下字段,以查询将Lead发送到哪些商店。我知道条件的链接不正确,但无法弄清楚如何重新格式化以正确发送。任何帮助都将非常感谢,谢谢!
def build_filters_obj
filters = []
filters.push 'location_north' if @lead.location_north
filters.push 'location_east' if @lead.location_east
filters.push 'location_south' if @lead.location_south
filters.push 'location_west' if @lead.location_west
filters.push 'location_other' if @lead.location_other
return filters
end
def perform(lead_id)
@lead = Lead.find(lead_id)
lead_email = ValidEmail2::Address.new(@lead.email)
UserNotifierMailer.send_signup_email(@lead).deliver if lead_email.valid?
@stores = Store.all
@stores = @stores.where.not(email: [nil, ''])
n = @lead.guests_total.to_i
@stores = @stores.where("capacity_min <= ? AND capacity_max >= ?", n, n)
@stores = @stores.where(:type_unique => true) if @lead.store_type_unique
@stores = @stores.where(:type_dining => true) if @lead.store_type_dining
@stores = @stores.where(:type_hotel => true) if @lead.store_type_hotel
filters = build_filters_obj
filters.each do |filter|
@stores = @stores.where(filter.to_sym => true)
end
@stores = @stores.or(Store.where(:receive_all => true))
@stores.each do |store|
store_email = ValidEmail2::Address.new(store.email)
UserNotifierMailer.send_lead_email(store, @lead).deliver if store_email.valid?
end
end
字符串
如果我的代码很糟糕,我道歉,Ruby不是我通常工作的地方,我肯定我犯了一些初学者的错误!
1条答案
按热度按时间xj3cbfub1#
我注意到的最大的代码气味是有很多if检查,这使得你的代码更难推理。试着创建哈希并调用方法来清理哈希。
我还建议你通过rubocop来传递这些代码,这会让你的代码看起来更地道,错误更少。
1.构建过滤器对象
字符串
也许我们至少可以让它准备好使用。在ruby习惯的命名方式中,这将是一个 * 名词 *,并直接使用它。注意,我们没有创建字符串,也没有在以后将它们转换为符号。
型
您可以构建一个哈希值,然后删除虚假值
型
因此,总体而言,这是您可以调用查询的方式
型
https://rubyapi.org/3.2/o/hash#method-i-filter