Vinicius Martinson
Vinicius Martinson

Reputation: 95

Refactoring in Ruby on Rails 4.2.3

I am trying to refactor my code to look cleaner. Right now I have this bad code:

@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

And I was trying to make it similar to this:

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

But I think I am missing some Ruby syntax, because I get this error:

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

It seems really simple. That's the problem when you first learn the framework and not the core language.

I thank you in advance.

Upvotes: 0

Views: 47

Answers (1)

Vrushali Pawar
Vrushali Pawar

Reputation: 3803

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

Try this code.

Upvotes: 3

Related Questions