skinny controllers in Rails
Your controller is so fat I took a screenshot of it last Christmas and it is still printing. We have all heard stories about how we should keep our controllers slim and fit but there can never be a definitive answer on how to accomplish the athletic pose. For you see, there are an infinite amount of ways that your controller can take on husk. In this blog-post I will attempt to define and solve one of these problems.
Let us suppose that you have a User model and a Job model.
class User < ActiveRecord::Base has_many :jobs end class Job < ActiveRecord::Base belongs_to :user end
Ok, so this proverbial Job is a very complex model. It has many attributes that are activated by complex algorithms. The job’s algorithms are influenced by input from the user.
class Job < ActiveRecord::Base belongs_to :user def algorithm!( input ) case input when :variation_one # do a bunch of crap when :variation_two # do even more crap end# case end# algorithm end# Job
Now that we have this model with extremely complicated algorithms that depends on loads of user input; we need to find a RESTful way to call these methods. Please keep in mind that these methods require the users input which will come from the params hash. Since our app is RESTful, we will be ‘updating’ the object by sending a PUT request with data that will be received by the Jobs controller.
Our edit.html.erb should have something like this in it:
<%= f.check_box :important_input_that_is_not_apart_of_the_model %>
This data’s purpose is to instruct the algorithm on how to execute. However, it is not apart of the model. There is NO column that corresponds to this data. So the question now becomes: How do i get this data from the view/controller (params hash) to the model?
The way I attack this problem is by adding this to my model:
class Job < ActiveRecord::Base belongs_to :user attr_accessor :important_input_that_is_not_apart_of_the_model def before_save self.algoritm!( self. important_input_that_is_not_apart_of_the_model ) end def algorithm!( input ) case input when :variation_one # do a bunch of crap when :variation_two # do even more crap end end# algorithm end# Job
In this case we have added NO extra code to our update method in the Jobs controller. However we have added heaps of functionality.
Let me know if there is better way to do this ?



