Umesh Kushwaha Umesh Kushwaha - 1 month ago 11
Ruby Question

What is the difference between Employee.last and Employee.last.decorate in Rails?

I didn't find any answer for this question after google. Please can anyone explain the difference between these two.

Answer

There is draper gem.
It allows you to decorate objects.
The aim is to move some methods which are related to object's presentation (and not related to business logic) out of model to some place (decorator).

For example given

# app/models/employee.rb
class Employee < ActiveRecord::Base
end

and

# app/decorators/employee_decorator.rb
class EmployeeDecorator < Draper::Decorator
  def foo
    p 'method from decorator is called'
  end
end

You can do the following

emp = Employee.new # would be Employee instance
emp.foo # would be error since Employee has no foo instance method
emp.decorate.foo # => would be 'method from decorator is called'

P.S.

Check out the gem docs. It's very well documented. Bet you will love it.

Comments