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

Repeating use of "v." annoys me. Do you see a nicer way?

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

Problem

This code smells to me, but I don't see the way to clean it up. I see v. mentioned over and over. Any hints would be appreciated!

#
  # Create a new Value if it doesn't already exist, and initialize the attributes per
  # the parameters of the call.
  #
  def self.find_or_create_value(prog_id, part_id, round_id, quest_id, new_value=nil)
    prog = Program.find(prog_id)
    attrs = {participant_id: part_id, round_id: round_id, question_id: quest_id}
    v = prog.values.where(attrs).first
    if v.nil?
      v = prog.values.build
      v.assign_attributes(attrs, without_protection: true)
    end
    v.value = new_value
    v.save
    v
  end
end

Solution

You can use rails find_or_initialize_by method. Here is example:

def self.find_or_create_value(prog_id, part_id, round_id, quest_id, new_value=nil)
    prog = Program.find(prog_id)
    prog.values.find_or_initialize_by_participant_id_and_round_id_and_question_id(part_id, round_id, quest_id) do |v|
      v.value = new_value
      v.save
    end
  end

Code Snippets

def self.find_or_create_value(prog_id, part_id, round_id, quest_id, new_value=nil)
    prog = Program.find(prog_id)
    prog.values.find_or_initialize_by_participant_id_and_round_id_and_question_id(part_id, round_id, quest_id) do |v|
      v.value = new_value
      v.save
    end
  end

Context

StackExchange Code Review Q#18451, answer score: 4

Revisions (0)

No revisions yet.