Skip to content

Instantly share code, notes, and snippets.

@iyuuya
Last active January 9, 2018 10:39
Show Gist options
  • Save iyuuya/8786696b9bd3f9cb009ebebc8bebd40e to your computer and use it in GitHub Desktop.
Save iyuuya/8786696b9bd3f9cb009ebebc8bebd40e to your computer and use it in GitHub Desktop.
refine test
#===============================================================================
# app/models/*.rb
#===============================================================================
class Company
has_many :users
has_many :admins
end
class User
belongs_to :company
end
class Admin
belongs_to :company
end
#===============================================================================
# app/jobs/hoge_job.rb
#===============================================================================
class HogeJob < ApplicationJob
# Company, Admin, Userそれぞれ#to_hで同じキーを持つHashにしたい
# ほぼ100%このHogeJobでしか使わないので、中に入れたい気持ちがある
module BenriModule
refine Company do
def to_h
{ email: contact_email, lang: default_lang, type: 'admin', company_code: code }
end
end
refine Admin do
def to_h
{ email: email, lang: lang, type: 'admin', company_code: company.code }
end
end
refine User do
def to_h
{ email: email, lang: lang, type: 'service', company_code: company.code }
end
end
end
using BenriModule
def perform(type)
# to_hしたものをメーラーに渡したい
announcemt_targets(type).each { |target| SugoiMailer.say_hello(target).deliver_later }
end
private
def announcemt_targets(type)
case type
when 'company' then admins + company_contacts
when 'user' then users
end
end
# モデル毎にスコープが違う
def admins
Admin.hoge.map(&:to_h) # NoMethodError
end
def company_contacts
Company.fuga.map(&:to_h) # NoMethodError
end
def users
User.piyo.map(&:to_h) # NoMethodError
end
end
@iyuuya
Copy link
Author

iyuuya commented Jan 9, 2018

.map(&:to_h)  .map { |a| a.to_h }

にすれば動いた
でもrubocopに怒られるのでつらい…

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment