HiveBrain v1.2.0
Get Started
← Back to all entries
patternrubyrailsMinor

Refactoring if statement based on a hash key

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
refactoringstatementhashbasedkey

Problem

I have to call Article.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
end


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:

{ 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 find

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]
end

Code 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]
end

Context

StackExchange Code Review Q#116122, answer score: 3

Revisions (0)

No revisions yet.