Sunday, 15 June 2014

ruby on rails - method to keep the code DRY -



ruby on rails - method to keep the code DRY -

i have project creation form creates new project in have parameters come array these 3 attributes, need convert string ',' using bring together method, , doing following:

@project.trackers = @project.trackers.join(',') if !@project.trackers.nil? @project.modules = @project.modules.join(',') if !@project.modules.nil? @project.custom_fields = @project.custom_fields.join(',') if !@project.custom_fields.nil? @project.repository = @project.repository.join(',') if !@project.repository.nil?

as using same logic variables create method pass arguments , in 1 line.

any suggestions helpful.

tried:

array = ['trackers','modules','custom_fields','repository'] joiner(array) #method phone call def joiner(args) args.each |param| if !param.nil? @project.param = @project.param.join(',') # stuck how convert param string end end end

metaprogramming rescue:

%w(trackers modules custom_fields repository).each |field| @project.send("#{field}=", @project.send(field.to_sym).join(',')) if @project.send(field.to_sym) end

update

there very book if solve type of problems pro.

ruby-on-rails ruby

No comments:

Post a Comment