0
0

More than 3 years have passed since last update.

.present?はnilかそうじゃないか、という場合は不要

Last updated at Posted at 2019-12-18

キャンペーンコードから適用されるキャンペーンとプランに紐づくキャンペーンがあるんだけど、キャンペーンコードからのキャンペーンを配列の一番最初に表示させたかった時の実装。

辞書型(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
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0