キャンペーンコードから適用されるキャンペーンとプランに紐づくキャンペーンがあるんだけど、キャンペーンコードからのキャンペーンを配列の一番最初に表示させたかった時の実装。
辞書型(hash型)なのが注意。
key
でキャンペーンコードからのものを探して一旦削除してunshift
で先頭にpushしてるんだけどいまいち納得いってない。。もっといい方法ないのかな?
修正前
order_base_decorator.rb
def order_campaigns
c = options['campaigns'].to_a
cc = c.find{|x| x["key"] == "campaign-code"}
c.delete(cc) if cc.present?
c.unshift(cc) if cc.present?
if c.present?
unless c.first == {} || cc
return c.unshift({}).to_a
end
return c
end
return c
end
修正後
order_base_decorator.rb
def order_campaigns
c = options['campaigns'].to_a
cc = c.find{|x| x["key"] == "campaign-code"}
# cのなかで見つからなかったらccはnil
if cc
c.delete(cc)
c.unshift(cc)
end
if c.present?
unless c.first == {} || cc
return c.unshift({}).to_a
end
return c
end
return c
end
メソッド修正された
order_base_decorator.rb
def order_campaigns
campaigns = options['campaigns'] || []
cc = campaigns.find{|hash| hash["key"] == 'campaign-code'}
if cc
campaigns.select{|hash| hash["key"] != 'campaign-code'}.unshift(cc)
end
campaigns
end