patternrubyMinor
Merging with different modules
Viewed 0 times
withdifferentmodulesmerging
Problem
We have an action merge for two projects. In the projects we have different modules like Feed, Files, Post etc....
Is this correct way to handle this action ? How can I handle this in a better way ?
modules Convert
class Merge
attr_accessor :source_ids, :destination_id, :sources, :destination
def initialize(source_ids, destination_id)
@source_ids = source_ids.class == Array ? source_ids : [source_ids]
@destination_id = destination_id
@sources = Modelname.where("id in (?)", @source_ids).all
@destination = Modelname.where("id in (?)", @destination_id).first
end
def merge
sources.each do |source|
ActiveRecord::Base.transaction do
Convert::Feed.new(source, destination).merge
Convert::File.new(source, destination).merge
Convert::Post.new(source, destination).merge
## There are many more modules - code comes here
end
end
end
end
class Feed
def initialize(source, destination)
@source = source
@destination = destination
end
def merge
#Feed merge code here
end
end
class File
def initialize(source, destination)
@source = source
@destination = destination
end
def merge
#File merge code here
end
end
class Post
def initialize(source, destination)
@source = source
@destination = destination
end
def merge
#Post merge code here
end
end
end
a = Convert::Merge.new(source_id, destionation_id)
a.mergeIs this correct way to handle this action ? How can I handle this in a better way ?
Solution
This is nowhere near the full answer, but I just want to touch on the initialize method of Merge real quick since it was the first thing to jump out to me.
This code is functionally equivalent. Using the splat operator at the end I guarantee the source ids will be in an array. I'll keep looking at the rest of the code and go from there, but that was the first thing I wanted to point out.
def initialize(destination_id, *source_ids)
@source_ids = source_ids
@destination_id = destination_id
@sources = Modelname.where(id: @source_ids).all
@destination = Modelname.where(id: @destination_id).first
endThis code is functionally equivalent. Using the splat operator at the end I guarantee the source ids will be in an array. I'll keep looking at the rest of the code and go from there, but that was the first thing I wanted to point out.
Code Snippets
def initialize(destination_id, *source_ids)
@source_ids = source_ids
@destination_id = destination_id
@sources = Modelname.where(id: @source_ids).all
@destination = Modelname.where(id: @destination_id).first
endContext
StackExchange Code Review Q#52093, answer score: 3
Revisions (0)
No revisions yet.