Search code examples
rubysinatraruby-datamapper

What is the best way to save an array into a hash dynamically?


DataMapper saves its errors as a Validate::ValidationErrors object. I want to convert those errors to an array and save the errors indexed by the name of the new item being created (category). I am new to Ruby and looking for some guidance in regards to refactoring how the errors are saved in the return value. Any advice would be welcomed.

Specifically, I just don't feel that these lines look optimal:

....

# save error set as hash
data[:errors][clean] = Hash.new unless not data[:errors][clean].nil?
data[:errors][clean] = cat.errors.to_a.join(', ')

....

Here is the entire method

def self.createMany( input )

  # convert everything to lowercase
  categories = input.downcase

  data = {:errors => Hash.new, :success => Array.new }

  # convert input into array
  categories.split(',').each do |c|

    # remove leading and trailing white spaces
    clean = c.strip 

    # init new category
    cat = Category.new(:name => clean)

    # save cat
    if cat.save
      data[:success] << "#{clean} created"
    else
      # save error set as hash
     data[:errors][clean] = Hash.new unless not data[:errors][clean].nil?
     data[:errors][clean] = cat.errors.to_a.join(', ')
    end
  end

  data

end

Solution

  • There is not need for this line

    data[:errors][clean] = Hash.new unless not data[:errors][clean].nil?
    

    You can do just like the following examples

    > data = {:errors => {}, :success => []}
    # => {:errors=>{}, :success=>[]} 
    > data[:errors]["cat1"] = "error 1"
    # => "error 1" 
    > data[:errors]["cat2"] = "error 2"
    # => "error 2" 
    > data
    # => {:errors=>{"cat1"=>"error 1", "cat2"=>"error 2"}, :success=>[]}