Skip to content

Instantly share code, notes, and snippets.

@kalleth
Created November 20, 2012 11:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kalleth/4117343 to your computer and use it in GitHub Desktop.
Save kalleth/4117343 to your computer and use it in GitHub Desktop.
Refactor attempt following SRP
def do_bulk_creation # Controller action called from request
prize = Prize.find_by_id(params[:code][:prize_id])
codes = params[:code][:codes].split("\r\n").each{ |c| c.strip }
if bulk_creation_valid?(prize, codes)
perform_bulk_creation(prize, codes)
else
set_bulk_creation_error(prize, codes)
@bulk = Code.new(params[:code])
render :action => :bulk_create
end
end
private
def bulk_creation_valid?(prize, codes)
!prize.nil? && prize.digital && codes.size > 1
end
def perform_bulk_creation(prize, codes)
codes.each do |code|
prize.codes.create(code: code)
end
flash[:notice] = "Created #{codes.size} codes for prize #{prize.description}"
redirect_to :action => :index
end
def set_bulk_creation_error(prize, codes)
flash[:error] = if prize.nil?
"You must select a prize"
elsif !prize.digital
"You can only add codes for digital prizes"
elsif codes.size < 1
"You must enter some codes"
end
end
@judofyr
Copy link

judofyr commented Nov 20, 2012

def bulk_creation_valid?(prize, codes)
  if prize.nil?
    flash[:error] = "You must select a prize"
  elsif !prize.digital
    flash[:error] = "You can only add codes for digital prizes"
  elsif codes.size < 1
    flash[:error] = "You must enter some codes"
  end
  flash[:error].nil?
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment