Last active
January 9, 2018 10:39
-
-
Save iyuuya/8786696b9bd3f9cb009ebebc8bebd40e to your computer and use it in GitHub Desktop.
refine test
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#=============================================================================== | |
# 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
にすれば動いた
でもrubocopに怒られるのでつらい…