Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Decorators in Rails

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 176
    Comment on it

    We use Decorators for cleaning up view logic and models of a rails application. So if we use decorators, models and views would be less complex. When we use decorator for a project we might have a 1:1 mapping between models and decorators which means all the presentation logic of a Blog would be in BlogDecorator.
    Draper gem is used for this approach.
    Draper adds an object-oriented layer of presentation logic to Rails application.

    Add Draper to your Gemfile and run bundle install

    gem 'draper', '~> 1.3'

    Decorators resides in app/decorators directory and name of a decorator is mapped with the model they are decorating as shown in example below.

    # app/decorators/blog_decorator.rb
     

    class BlogDecorator < Draper::Decorator
        def published_at
        object.published_at.strftime("%A, %B %e")
      end
    end

    So we have created a decorator "BlogDecorator". Now we are going to use this.

    @blog = BlogDecorator.new(Blog.first)

    If you want to create a decorator for a controller by default, Run the generate command below.

    rails generate resource Blog

    And it will create the BlogDecorator for you along with the appropriate tests.
    Draper supports RSpec, MiniTest::Rails, and Test::Unit.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: