M
M
Mr Freeman2015-06-30 19:50:30
Ruby on Rails
Mr Freeman, 2015-06-30 19:50:30

Rubies, help me out! How to refactor the following method?

Here is the code:

def generate_link(campaign_id)

    source = self.find(campaign_id).source

    params = {}
    if source.sub1 != ''
      params[:sub1] = @source.sub1
    end
    if source.sub2 != ''
      params[:sub2] = @source.sub2
    end
    if source.sub3 != ''
      params[:sub3] = @source.sub3
    end
    if source.sub4 != ''
      params[:sub4] = @source.sub4
    end
    if source.sub5 != ''
      params[:sub5] = @source.sub5
    end
    if source.sub6 != ''
      params[:sub6] = @source.sub6
    end

    @link = Settings.tds.url + campaign_id + (params.present? ? ('?' + params.to_query) : '')
  end

I'm just not familiar with such tools in ruby ​​yet. But I would do it like this -
Declared a variable (or pulled it out of Settings)
subs = [sub1, sub2, sub3, sub4, sub5, sub6]
Then for each I would do something similar, in the style of php::array_map() and get a new array, depending on the presence of source.sub1-6
and how would people make a similar code here, whom my code smiles at? :)
PS: "ruble" for about a week in total, so don't swear

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
thepry, 2015-06-30
@vladamir

Even so :)

[:sub1, :sub2, :sub3, :sub4, :sub5, :sub6].each{ |sub| params[sub] = @source[sub] if @source[sub].present? }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question