patternrubyrailsMinor
Refactoring if statement based on a hash key
Viewed 0 times
refactoringstatementhashbasedkey
Problem
I have to call Article.
I do, however, have no idea to implement it properly.
The code works, but the number of possible states of an article will probably grow in the future.
I would like to have a hash like this:
and let
to_draft/to_archive/publish method depending on the presence of the corresponding key in the params hash.I do, however, have no idea to implement it properly.
def update_state
method = if params[:draft].present?
:to_draft
elsif params[:archived].present?
:to_archive
else
:publish
end
@article.send method
endThe code works, but the number of possible states of an article will probably grow in the future.
I would like to have a hash like this:
{ draft: :to_draft, archived: :to_archive, default: :publish }and let
#update_state decide what should be called, based on the params hash.Solution
I suggest using
findARTICLE_ACTIONS = { :draft => :to_draft,
:archived => :to_archive,
:default => :publish
}
def update_state
state = [:draft, :archived, :default]
.find {|state| params[state].present?}
@article.send ARTICLE_ACTIONS[state]
endCode Snippets
ARTICLE_ACTIONS = { :draft => :to_draft,
:archived => :to_archive,
:default => :publish
}
def update_state
state = [:draft, :archived, :default]
.find {|state| params[state].present?}
@article.send ARTICLE_ACTIONS[state]
endContext
StackExchange Code Review Q#116122, answer score: 3
Revisions (0)
No revisions yet.