2015-09-12 68 views
0

我試圖重構我的代碼以使其看起來更乾淨。 現在我有這個代碼:Ruby on Rails中的重構4.2.3

@member = Member.new 

@member.build_local_board 
@member.build_prospective 
@member.build_alumni 
@member.build_board 
@member.build_job 
@member.build_academic 
@member.build_special_role 
@member.build_conferences_member 

@prospective = Prospective.new 
@alumni = Alumni.new 
@board = Board.new 
@user = User.new 
@job = Job.new 
@academic = Academic.new 

我試圖使它與此類似:

models = %w(local_board, prospective, alumni, board, [...]) 
fields = [models] 
fields.each do |f| 
    @f = f.new 
    @member.build_f 
end 

但我覺得我缺少一些的Ruby語法,因爲我得到這個錯誤:

undefined method 'new' for ["local_board,", "prospective"]:Array

看起來很簡單。當你第一次學習框架而不是核心語言時,這就是問題所在。

我提前感謝你。

回答

3
models = %w(local_board prospective alumni board) 
models.each do |f| 
    klass = f.camelize.constantize 
    instance_variable_set("@#{f}", klass.new) 
    @member.send("build_#{f}".to_sym) 
end 

試試看看這個代碼。

+0

**完美工作**,非常感謝。我可能應該看看文檔。 Ruby學習所有這些.camelize,.constantize,.send。再次感謝! –