AnthonyGalli.com AnthonyGalli.com - 1 month ago 10
Ruby Question

Where to put long conditional statement that changes attribute in create?

If a challenge is created with

name: "Run a Mile"
then how can we make the boolean
key: true
?

*There are upwards of 50 names that I want to pass
key
to true, above just an example.

I figured I would do it in
create
, but then isn't that a lot of logic to go in the controller? Not sure if it should go in the model somehow but I also worry that's a lot of lines for there too.

def create
@challenge = current_user.challenges.build(challenge_params)
### Where should I put the below? ###
if @challenge.name == "Run a Mile"
@challenge.key = true
elsif @challenge.name == "Meditate 5 Min"
@challenge.key = true
elsif @challenge.name == "Tour Capital Building"
@challenge.key = true
elsif @challenge.name == "See Statue of Liberity"
@challenge.key = true
elsif @challenge.name == "Pait a Picture"
@challenge.key = true
else
end
### Where should I put the above? ####
if @challenge.conceal == true
@challenge.save
redirect_to @challenge
if @challenge.category == 'goal'
flash[:info] = 'CHALLENGE SECRETLY SAVED'
else
flash[:info] = "CHALLENGE SECRETLY SAVED. DON'T STRIKE OUT!"
end
elsif
@challenge.save
track_activity @challenge
redirect_to @challenge
if @challenge.category == 'goal'
flash[:info] = 'CHALLENGE SAVED'
else
flash[:info] = "CHALLENGE SAVED. DON'T STRIKE OUT!"
end
else
respond_modal_with @challenge
end
end


As you can see my
create
action is already getting complex and this isn't even the full version of it.

Answer

I would do that in model Challenge (I suppose) as

1) if you need change key every time as name change

def name=(val)
  ...
  case name
  when 'a', 'b'
    self.key = true
  end
  ... # return with calling super method
end

2) if you need change key only in this place

def reset_key
  case name
  when 'a', 'b'
    self.key = true
  end
end

# then @challenge.reset_key in controller

3) or you can avoid setting key (why we need more state?)

def key
  case name
  when 'a', 'b'
    true
  end
end
Comments