Ruby on Rails: If you have 50 if-else statements in your after_create action, will this slow down your application?

Is using 50 if-else commands too resource intensive for a single action?

I am doing something like this:

if team.players.count > 1
   assign_team_type(..)
elsif team.players.count > 3
   assign_team_type(..)
...
etc.
...
end

Also, is it more efficient to place 50 if-else statements in your create action inside your controller instead of the after_create method? Or would it be more efficient to use a switch case statement instead or just avoid it altogether?

EDIT: Thanks for the very quick answers! The code is designed to host a community sports tournament to assign teams based on the number of players in that team. I am trying to write something that assigns a team type to each team depending on how many players are added to this team. Thus, there are teams for 1 player, 3 players, 5 players, 7 players, etc., up to 200 players, which requires only 50 if-else teams.

Operations are performed in player_controller after the user visits http: // localhost / players / new , adds the player, and then the application decides which team to assign their team based on how many players are currently in this team. This is very straight forward (a basic CRUD application that needs only these 50 if-else statements)

models:

Team (has_many :players)
Player (belongs_to :team)

scaffold team name:string team_type:string
scaffold player team_id:integer name:string

:)

+3
6


assign_team_type(case team.players.count
                 when 2    then ...
                 when 3..5 then ...
                 else raise "Assignment failed"
                 end
)

, , , team.players.count . , . .

+9

, . , , , , - .

? - :

TeamTypes = { 1 => something, 2 => something_else, .. }

assign_team_type( TeamTypes[team.players.count] )
+7

max_players team_types - :

find(:first, :conditions => ["max_players < ?", self.player_count], :order => "max_players ASC")

, -.

+3

, 2D-, :

x=[[1, "arg 1"],
   [3, "arg 2"],
   [9, "arg 3"],
   ...
  ]

- , - , assign_team_type.

, , - :

func_arg = x.collect{|w| w[0] < team.players.count ? w[1] : nil}.compact.last
assign_team_type(func_arg)

C- , " ", .

+2

/dict?

d={1:assign_team_type(1),2:assign_team_type(2)}
+1

" "

if-else , , , , .

I would recommend refactoring any excessively large branching sections into good clean statement instructions.

0
source

Source: https://habr.com/ru/post/1731386/


All Articles