开发者

How can I refactor a simple dynamic attribute?

I have a form that handles four different types of facets of the same form. In my SQL column, I have the four different attributes.

Only one of them is going to have data in it.

Distribution  =>
   zip_code: nil
   me_topic: nil
   sex: nil
   age: nil

In order to differentiate between them, I wanted to set up a case statement, and add a dynamic attribute to the create call :

@type = case params[:type]
  when "zip"      then ":zip_code"
  when "interest" then ":me_topic"
  when "sex"      then ":sex"
  when "age"      then ":age"
end
@cur_item = Distribution.new(@type => params[:value])

# Unf开发者_运维百科ortunately, this is not the proper way to create a dynamic attribute


@distribution = @email.distributions.create(params[:distributions])  

What is the proper syntax for completing this statement?


Declare a method called type_map

def type_map params
  @@type_map ||= {
    "zip"      => :zip_code, 
    "interest" => :me_topic, 
    "sex"      => :sex, 
    "age"      => :age
  }
  { @@type_map[params[:type]] => params[:value]
end

Now you can use the map as follows:

@distribution = @email.distributions.create(type_map(params)) 


This is what I went with, but feel free to best my answer.

  @cur_item = case params[:type]
    when "zip"      then {:zip_code => params[:value]}
    when "interest" then {:me_topic => params[:value]}
    when "sex"      then {:sex => params[:value]}
    when "age"      then {:age => params[:value]}
  end

  @distribution = @email.distributions.create(@cur_item)  


Well, one way to improve your code (what you posted in your answer) would be to factor out the repeated params[:value] as follows:

key = case params[:type]
  when "zip"      then :zip_code
  when "interest" then :me_topic 
  when "sex"      then :sex
  when "age"      then :age
end

@cur_item = { key => params[:value] }
@distribution = @email.distributions.create @cur_item
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜