Topic: [SOLVED] Refactor taking a value method, converting, and incrementing

Here's my code, it explains what I'm trying to refactor:

  #Explains itself!
  def print_number
    # Get the data
    @option = Option.find_by_name('next_number')
    
    # Put the value from the returned data into a local variable
    # so we can convert it to an Integer.
    integer_value = @option.value
    integer_value = integer_value.to_i + 1
    
    # Update the option value with the incremented value from above.
    @option.value = integer_value
    
    # Save the option so we can increment it again on the next function call
    @option.save
    
    # Return the new value
    integer_value
  end

I would like to do something like @option.value += 1, but I cannot do that. How can I refactor this to make it look better?

Thanks

Last edited by wesf90 (2012-03-12 20:02:41)

Remember to edit your topic title and add "[SOLVED]" if your question has been answered!

Follow me!

Re: [SOLVED] Refactor taking a value method, converting, and incrementing

def print_number
    @option = Option.find_by_name('next_number')
    if @option
      @option.update_attribute :value, @option.value.succ
      @option.reload.value
    end
  end

Re: [SOLVED] Refactor taking a value method, converting, and incrementing

Just one more remark: as he expects an Integer, you should add the conversion to_i before calling 'succ' method:

 @option.update_attribute :value, @option.value.to_i.succ

Re: [SOLVED] Refactor taking a value method, converting, and incrementing

succ can work with string variables too.
>> "asd-0001123".succ
=> "asd-0001124"

Re: [SOLVED] Refactor taking a value method, converting, and incrementing

Sure, it can. I précised it just in case because wesf90 in his post  expected an integer value, so any way he should convert it later so that is could be accepted by his DB.

Re: [SOLVED] Refactor taking a value method, converting, and incrementing

Thanks guys, the tips worked great. Took my real code from 20 lines down to 10 smile

Remember to edit your topic title and add "[SOLVED]" if your question has been answered!

Follow me!