0

I have code similar to follwoing

...
@c = M.find(params[:id]).c.find(params[:c_id])
if @c.s.count > 0
  @s = @c.s.sort_by{|e| e[:order]}.first
  unless @s.p.nil?
    @img = @s.p.image_file.remote_url
  else
    @s.p = P.new
    @img = request.protocol + request.host_with_port + "/none.png"  
  end
  unless @s.a.nil?
    @voice = @s.a.audio_file.remote_url
  else
    @s.a = A.new
  end
else
 ...  
end
@c_v_url = ""
unless @c_v_url.nil?
  @c_v_url = @c.v_o.a_file.remote_url
else
  @c.v_o = A.new
end  
@c_m_url = ""
unless @c_m_url.nil?
  @c_m_url = @c.b_m.a_file.remote_url
else
  @c.b_m = A.new
end
...

Now all the instance variables are to be used in the view and I want to re-factor the code to make the Controller skinny. What will be the best approach to do the re-factoring? Will it be wise to move this code to the Model?

2 Answers 2

1

I can't really see what this code is used for, but it looks like view logic to display images, file and audio links?

I'd create a view helper method for each one, for example:

 def s_image_url(s)
   unless s.p.nil?
     s.p.image_file.remote_url
   else
     request.protocol + request.host_with_port + "/none.png"  
   end
 end

For more info on view helpers

Sign up to request clarification or add additional context in comments.

1 Comment

This partially solves my problem, but where do I move this complete if/else logic if I have to.
0

I would use the Presenter Pattern, here are some resources for explanation (there are a lot more out there):

  1. http://blog.jayfields.com/2007/03/rails-presenter-pattern.html
  2. http://kpumuk.info/ruby-on-rails/simplifying-your-ruby-on-rails-code

Short story: You put all your logic for retrieving your models in the presenter. The presenter is easy to test and extensible. In your controller action will have only one line of code to instantiate the presenter.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.