Hi friends today I am going to guide you how you can make our controller skinny by following some basic object oriented approach in rails. Often we start writing our program business logic in our controller thus making mess of our controller as the business logic keeps on increasing it becomes difficult to manage it. Lets explain you by taking a simple example:
class User
validates_uniqueness_of :email
end
class RegistrationController < ApplicationController
def create
user = User.where("username = ?", params[:username]).first
user ||= User.new.tap do |new_user|
new_user.username = params[:email]
new_user.save!
end
render json: user
end
end
Above example is a very simple example of registeration where we only need to pass email which should be unique. Based on email being unique code will either create new user or return already created user.
The first improvement we can do to the above code is that :
class User
validates_uniqueness_of :username
def self.register(email)
user = User.where("username = ?", params[:username]).first
user ||= User.new.tap do |new_user|
new_user.username = email
new_user.save!
end
end
end
class RegistrationController < ApplicationController
def create
user = User.register(params[:email])
render json: user
end
end
This is a point where you have transferred all your business logic to model thus now you can simply call User.register(params[:email]) from your controller and model have a method defined which take care of your logic. The above approach seems to be fine till now but as your project grows so does your business logic so will length of your model. In order to take away lengthy model logic we can create services which take care of any lengthy logic like registration/create profile etc in which we need to check number of things before saving it in db.
Thus we create a new file know as services with name RegistrationService which will take care of all our database interaction while user registers on the site :
class RegistrationService
def register(email)
user = User.where("username = ?", params[:username]).first
user ||= User.new.tap do |new_user|
new_user.username = email
new_user.save!
end
end
end
class RegistrationController < ApplicationController
before_filter :load_registration_service
def create
user = @registration_service.register(params[:email])
render json: user
end
def load_registration_service(service = RegistrationService.new)
@registration_service ||= service
end
end
Now we have a new class RegistrationService which take care of our business logic and thus our controller/model becomes skinny.
0 Comment(s)