Leo
Leo

Reputation: 2103

passing a block into create method in Ruby

I want to write a method which will work like this one

def create_new_car(salon)
    Car.create name: salon.offer.name, description: salon.offer.description, photo: salon.offer.photo, dealer_id: salon.dealer_id
end

but i want to keep it DRY. is there a way to pass those attributes by, i dont know, iterating through array of attributes by passing a block?

Upvotes: 1

Views: 193

Answers (2)

nicosantangelo
nicosantangelo

Reputation: 13716

You can pass a block to create:

def create_new_car(salon)
    Car.create do |car|
        car.name = salon.offer.name
        car.description = salon.offer.description
        car.photo = salon.offer.photo
        car.dealer_id = salon.dealer_id
    end
end

You could also set some attributes as the first parameter and then pass a block:

    Car.create(name: salon.offer.name) do |car|
        car.description = salon.offer.description
        #...
    end

You can implement any logic you want inside that block to assign the Car properties, like this:

    attributes = ["name", "description", "photo", "dealer_id"]
    Car.create do |car|
        attributes.each { |a| car.send( "#{a}=", salon.offer.send(a) )
    end

Upvotes: 1

Rajarshi Das
Rajarshi Das

Reputation: 12320

Please try this

array_of_attrbiutes = [{name: salon.offer.name...}, {name: }, {}...]    
 def create_new_car(array_of_attributes)  
  Car.create array_of_attributes
 end  
end  

Please see https://github.com/rails/rails/blob/b15ce4a006756a0b6cacfb9593d88c9a7dfd8eb0/activerecord/lib/active_record/associations/collection_proxy.rb#L259

Upvotes: 0

Related Questions