0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Ruby Classの継承を使ってみた。

0
Last updated at Posted at 2020-04-30

どうもチャンクノです。
今回はClassの継承を使ってみた話です。
ぶっちゃけ今までどういうところで使えばいいか分かってなかったんですよね。
でも個人開発している中で、ここで使うんじゃね?ってタイミングがあったので使ってみました!

自分の作っているアプリにはTradeモデルがあり、最初はそこに勝率を求めるメソッドを書いていました。

class Trade < ApplicationRecord
  attr_accessor :current_user_id

  def search_user_fx_trades
    Trade.where("(user_id = ?) and (trade_category_id = ?)", current_user_id, 1)
  end

  def win_number_of_fx_trades
    search_user_fx_trades.where("result" => "資産増")
  end

  def win_number_of_fx_daytrades
    win_number_of_fx_trades.where("trade_style_id" => 1).count
  end

  def daytrade_win_rate
    return "0%" if win_number_of_fx_daytrades === 0
    "#{(win_number_of_fx_daytrades / search_user_fx_trades.count.to_f * 
  100).floor(1)}%"
  end

  def fx_win_rate
    return "0%" if win_number_of_fx_trades.count === 0
    "#{(win_number_of_fx_trades.count / search_user_fx_trades.count.to_f * 
     100).floor(1)}%"
  end
end

ほんとはもっと書いてあるんですけど長くなってしまうのでこのぐらいに。
Tradeって他にもスイングトレードとスキャルピングトレードっていうのがあるんですがそれを書き終えた時に、このままいくとメソッドの数えぐいことになるなと気づきました。
まだ年単位や週単位のメソッドが残っていたので。
そこでClassの継承の出番か?と思い新たにClassを作成しました。

class Fx < Trade

  def win_number_of_fx_daytrades
    win_number_of_fx_trades.where("trade_style_id" => 1).count
  end

  def daytrade_win_rate
    return "0%" if win_number_of_fx_daytrades === 0
    "#{(win_number_of_fx_daytrades / search_user_fx_trades.count.to_f * 100).floor(1)}%"
  end
  
end

こんな感じ。
書き方は子クラス < 親クラスです。
これでFxクラスでもTradeクラスのメソッドが使えるようになりました。
子クラスは親クラスの全てを引き継ぐので、attr_accessor :current_user_idなどを、改めて子クラスに記載する必要はありません。
注意点としては、DayTrade内にあるメソッドなので新たにDayTradeインスタンスを作成することと、作成したインスタンスにcurren_userを引数に取らなければいけないということです。

@fx = Fx.new(current_user)
こうすると

@fx.day_trade_win_rate
こんな感じで呼び出せるようになる。

使用する場面があってるかは分かりませんが、こういう感じでそれぞれまとめることで分かりやすくなるんじゃないかなと思います!
なんかメソッドがめちゃくちゃ増えて分かりにくいなと感じてきたら別クラスに切り出せないか検討してみましょう!!
あ、ちなみにちゃんとTrade.rbというファイルとは別にFx.rbというファイルを作ってくださいね!
そんなこと分かってるとは思いますが念の為😌

それでは今日はこの辺で!
皆様よきプログラミングライフを🙏

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?