Reputation: 430
I have a project creation form which creates a new project where in I have the parameters come as an array for these 3 attributes, which I need to convert to a string with a ',' using the join method, and I am doing the following:
@project.trackers = @project.trackers.join(',') if [email protected]?
@project.modules = @project.modules.join(',') if [email protected]?
@project.custom_fields = @project.custom_fields.join(',') if [email protected]_fields.nil?
@project.repository = @project.repository.join(',') if [email protected]?
As I am using the same logic for all the variables I would like to create a method which will pass some arguments and do this in one line.
Any good suggestions will be very helpful.
Tried:
array = ['trackers','modules','custom_fields','repository']
joiner(array) #method call
def joiner(args)
args.each do |param|
if !param.nil?
@project.param = @project.param.join(',')
# Stuck how to convert param string
end
end
end
Upvotes: 1
Views: 42
Reputation: 2963
Metaprogramming to the rescue:
%w(trackers modules custom_fields repository).each do |field|
@project.send("#{field}=", @project.send(field.to_sym).join(',')) if @project.send(field.to_sym)
end
Update
There is a very good book if you like to solve this type of problems like a pro.
Upvotes: 2
Reputation: 168081
%w[trackers modules custom_fields repository].each do
|param|
unless (a = @project.send(param)).nil?
@project.send("#{param}=", a.join(","))
end
end
If you can live with the values being an empty string instead of nil
, then
%w[trackers modules custom_fields repository]
.each{|param| @project.send("#{param}=", @project.send(param).to_a.join(","))}
Upvotes: 2