{"id":14955564,"url":"https://github.com/akodkod/drape","last_synced_at":"2026-04-02T02:07:42.089Z","repository":{"id":65581498,"uuid":"59953125","full_name":"akodkod/drape","owner":"akodkod","description":"Drape – Reincarnation of Draper for Rails 5","archived":false,"fork":false,"pushed_at":"2016-05-29T19:59:34.000Z","size":119,"stargazers_count":58,"open_issues_count":1,"forks_count":2,"subscribers_count":3,"default_branch":"master","last_synced_at":"2026-03-16T01:52:21.127Z","etag":null,"topics":["decorators","gem","rails","rails5","ruby"],"latest_commit_sha":null,"homepage":"","language":"Ruby","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/akodkod.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2016-05-29T16:30:46.000Z","updated_at":"2023-10-18T07:14:43.000Z","dependencies_parsed_at":"2023-01-30T14:16:11.498Z","dependency_job_id":null,"html_url":"https://github.com/akodkod/drape","commit_stats":null,"previous_names":["mremelianenko/drape"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/akodkod/drape","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/akodkod%2Fdrape","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/akodkod%2Fdrape/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/akodkod%2Fdrape/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/akodkod%2Fdrape/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/akodkod","download_url":"https://codeload.github.com/akodkod/drape/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/akodkod%2Fdrape/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":31294398,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-02T01:43:37.129Z","status":"online","status_checked_at":"2026-04-02T02:00:08.535Z","response_time":89,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["decorators","gem","rails","rails5","ruby"],"created_at":"2024-09-24T13:11:22.545Z","updated_at":"2026-04-02T02:07:42.037Z","avatar_url":"https://github.com/akodkod.png","language":"Ruby","readme":"# Drape: View Models for Rails\n\n[![TravisCI Build Status](https://travis-ci.org/MrEmelianenko/drape.svg?branch=master)](http://travis-ci.org/MrEmelianenko/drape)\n[![Code Climate](https://codeclimate.com/github/MrEmelianenko/drape/badges/gpa.svg)](https://codeclimate.com/github/MrEmelianenko/drape)\n[![Inline docs](http://inch-ci.org/github/MrEmelianenko/drape.svg?branch=master)](http://inch-ci.org/github/MrEmelianenko/drape)\n\nDrape adds an object-oriented layer of presentation logic to your Rails\napplication.\n\nWithout Drape, this functionality might have been tangled up in procedural\nhelpers or adding bulk to your models. With Drape decorators, you can wrap your\nmodels with presentation-related logic to organise - and test - this layer of\nyour app much more effectively.\n\n## Drape this is Draper?\n\nYes, but Drape adapted for Ruby on Rails 5.\n\n## Why Use a Decorator?\n\nImagine your application has an `Article` model. With Drape, you'd create a\ncorresponding `ArticleDecorator`. The decorator wraps the model, and deals\n*only* with presentational concerns. In the controller, you decorate the article\nbefore handing it off to the view:\n\n```ruby\n# app/controllers/articles_controller.rb\ndef show\n  @article = Article.find(params[:id]).decorate\nend\n```\n\nIn the view, you can use the decorator in exactly the same way as you would have\nused the model. But whenever you start needing logic in the view or start\nthinking about a helper method, you can implement a method on the decorator\ninstead.\n\nLet's look at how you could convert an existing Rails helper to a decorator\nmethod. You have this existing helper:\n\n```ruby\n# app/helpers/articles_helper.rb\ndef publication_status(article)\n  if article.published?\n    \"Published at #{article.published_at.strftime('%A, %B %e')}\"\n  else\n    \"Unpublished\"\n  end\nend\n```\n\nBut it makes you a little uncomfortable. `publication_status` lives in a\nnebulous namespace spread across all controllers and view. Down the road, you\nmight want to display the publication status of a `Book`. And, of course, your\ndesign calls for a slighly different formatting to the date for a `Book`.\n\nNow your helper method can either switch based on the input class type (poor\nRuby style), or you break it out into two methods, `book_publication_status` and\n`article_publication_status`. And keep adding methods for each publication\ntype...to the global helper namespace. And you'll have to remember all the names. Ick.\n\nRuby thrives when we use Object-Oriented style. If you didn't know Rails'\nhelpers existed, you'd probably imagine that your view template could feature\nsomething like this:\n\n```erb\n\u003c%= @article.publication_status %\u003e\n```\n\nWithout a decorator, you'd have to implement the `publication_status` method in\nthe `Article` model. That method is presentation-centric, and thus does not\nbelong in a model.\n\nInstead, you implement a decorator:\n\n```ruby\n# app/decorators/article_decorator.rb\nclass ArticleDecorator \u003c Drape::Decorator\n  delegate_all\n\n  def publication_status\n    if published?\n      \"Published at #{published_at}\"\n    else\n      \"Unpublished\"\n    end\n  end\n\n  def published_at\n    object.published_at.strftime(\"%A, %B %e\")\n  end\nend\n```\n\nWithin the `publication_status` method we use the `published?` method. Where\ndoes that come from? It's a method of the  source `Article`, whose methods have\nbeen made available on the decorator by the `delegate_all` call above.\n\nYou might have heard this sort of decorator called a \"presenter\", an \"exhibit\",\na \"view model\", or even just a \"view\" (in that nomenclature, what Rails calls\n\"views\" are actually \"templates\"). Whatever you call it, it's a great way to\nreplace procedural helpers like the one above with \"real\" object-oriented\nprogramming.\n\nDecorators are the ideal place to:\n* format complex data for user display\n* define commonly-used representations of an object, like a `name` method that\n  combines `first_name` and `last_name` attributes\n* mark up attributes with a little semantic HTML, like turning a `url` field\n  into a hyperlink\n\n## Installation\n\nAdd Drape to your Gemfile:\n\n```ruby\ngem 'drape', '~\u003e 1.0.0.beta1'\n```\n\nAnd run `bundle install` within your app's directory.\n\nIf you're upgrading from a 0.x release, the major changes are outlined [in the\nwiki](https://github.com/drapegem/drape/wiki/Upgrading-to-1.0).\n\n## Writing Decorators\n\nDecorators inherit from `Drape::Decorator`, live in your `app/decorators`\ndirectory, and are named for the model that they decorate:\n\n```ruby\n# app/decorators/article_decorator.rb\nclass ArticleDecorator \u003c Drape::Decorator\n# ...\nend\n```\n\n### Generators\n\nWhen you have Drape installed and generate a controller...\n\n```\nrails generate resource Article\n```\n\n...you'll get a decorator for free!\n\nBut if the `Article` model already exists, you can run...\n\n```\nrails generate decorator Article\n```\n\n...to create the `ArticleDecorator`.\n\n### Accessing Helpers\n\nNormal Rails helpers are still useful for lots of tasks. Both Rails' provided\nhelpers and those defined in your app can be accessed within a decorator via the `h` method:\n\n```ruby\nclass ArticleDecorator \u003c Drape::Decorator\n  def emphatic\n    h.content_tag(:strong, \"Awesome\")\n  end\nend\n```\n\nIf writing `h.` frequently is getting you down, you can add...\n\n```\ninclude Drape::LazyHelpers\n```\n\n...at the top of your decorator class - you'll mix in a bazillion methods and\nnever have to type `h.` again.\n\n(*Note*: the `capture` method is only available through `h` or `helpers`)\n\n### Accessing the model\n\nWhen writing decorator methods you'll usually need to access the wrapped model.\nWhile you may choose to use delegation ([covered below](#delegating-methods))\nfor convenience, you can always use the `object` (or its alias `model`):\n\n```ruby\nclass ArticleDecorator \u003c Drape::Decorator\n  def published_at\n    object.published_at.strftime(\"%A, %B %e\")\n  end\nend\n```\n\n## Decorating Objects\n\n### Single Objects\n\nOk, so you've written a sweet decorator, now you're going to want to put it into\naction! A simple option is to call the `decorate` method on your model:\n\n```ruby\n@article = Article.first.decorate\n```\n\nThis infers the decorator from the object being decorated. If you want more\ncontrol - say you want to decorate a `Widget` with a more general\n`ProductDecorator` - then you can instantiate a decorator directly:\n\n```ruby\n@widget = ProductDecorator.new(Widget.first)\n# or, equivalently\n@widget = ProductDecorator.decorate(Widget.first)\n```\n\n### Collections\n\n#### Decorating Individual Elements\n\nIf you have a collection of objects, you can decorate them all in one fell\nswoop:\n\n```ruby\n@articles = ArticleDecorator.decorate_collection(Article.all)\n```\n\nIf your collection is an ActiveRecord query, you can use this:\n\n```ruby\n@articles = Article.popular.decorate\n```\n\n*Note:* In Rails 3, the `.all` method returns an array and not a query. Thus you\n_cannot_ use the technique of `Article.all.decorate` in Rails 3. In Rails 4,\n`.all` returns a query so this techique would work fine.\n\n#### Decorating the Collection Itself\n\nIf you want to add methods to your decorated collection (for example, for\npagination), you can subclass `Drape::CollectionDecorator`:\n\n```ruby\n# app/decorators/articles_decorator.rb\nclass ArticlesDecorator \u003c Drape::CollectionDecorator\n  def page_number\n    42\n  end\nend\n\n# elsewhere...\n@articles = ArticlesDecorator.new(Article.all)\n# or, equivalently\n@articles = ArticlesDecorator.decorate(Article.all)\n```\n\nDrape decorates each item by calling the `decorate` method. Alternatively, you can\nspecify a decorator by overriding the collection decorator's `decorator_class`\nmethod, or by passing the `:with` option to the constructor.\n\n#### Using pagination\n\nSome pagination gems add methods to `ActiveRecord::Relation`. For example,\n[Kaminari](https://github.com/amatsuda/kaminari)'s `paginate` helper method\nrequires the collection to implement `current_page`, `total_pages`, and\n`limit_value`. To expose these on a collection decorator, you can delegate to\nthe `object`:\n\n```ruby\nclass PaginatingDecorator \u003c Drape::CollectionDecorator\n  delegate :current_page, :total_pages, :limit_value, :entry_name, :total_count, :offset_value, :last_page?\nend\n```\n\nThe `delegate` method used here is the same as that added by [Active\nSupport](http://api.rubyonrails.org/classes/Module.html#method-i-delegate),\nexcept that the `:to` option is not required; it defaults to `:object` when\nomitted.\n\n[will_paginate](https://github.com/mislav/will_paginate) needs the following delegations:\n\n```ruby\ndelegate :current_page, :per_page, :offset, :total_entries, :total_pages\n```\n\n### Decorating Associated Objects\n\nYou can automatically decorate associated models when the primary model is\ndecorated. Assuming an `Article` model has an associated `Author` object:\n\n```ruby\nclass ArticleDecorator \u003c Drape::Decorator\n  decorates_association :author\nend\n```\n\nWhen `ArticleDecorator` decorates an `Article`, it will also use\n`AuthorDecorator` to decorate the associated `Author`.\n\n### Decorated Finders\n\nYou can call `decorates_finders` in a decorator...\n\n```ruby\nclass ArticleDecorator \u003c Drape::Decorator\n  decorates_finders\nend\n```\n\n...which allows you to then call all the normal ActiveRecord-style finders on\nyour `ArticleDecorator` and they'll return decorated objects:\n\n```ruby\n@article = ArticleDecorator.find(params[:id])\n```\n\n### When to Decorate Objects\n\nDecorators are supposed to behave very much like the models they decorate, and\nfor that reason it is very tempting to just decorate your objects at the start\nof your controller action and then use the decorators throughout. *Don't*.\n\nBecause decorators are designed to be consumed by the view, you should only be\naccessing them there. Manipulate your models to get things ready, then decorate\nat the last minute, right before you render the view. This avoids many of the\ncommon pitfalls that arise from attempting to modify decorators (in particular,\ncollection decorators) after creating them.\n\nTo help you make your decorators read-only, we have the `decorates_assigned`\nmethod in your controller. It adds a helper method that returns the decorated\nversion of an instance variable:\n\n```ruby\n# app/controllers/articles_controller.rb\nclass ArticlesController \u003c ApplicationController\n  decorates_assigned :article\n\n  def show\n    @article = Article.find(params[:id])\n  end\nend\n```\n\nThe `decorates_assigned :article` bit is roughly equivalent to\n\n```ruby\ndef article\n  @decorated_article ||= @article.decorate\nend\nhelper_method :article\n```\n\nThis means that you can just replace `@article` with `article` in your views and\nyou'll have access to an ArticleDecorator object instead. In your controller you\ncan continue to use the `@article` instance variable to manipulate the model -\nfor example, `@article.comments.build` to add a new blank comment for a form.\n\n## Testing\n\nDrape supports RSpec, MiniTest::Rails, and Test::Unit, and will add the\nappropriate tests when you generate a decorator.\n\n### RSpec\n\nYour specs are expected to live in `spec/decorators`. If you use a different\npath, you need to tag them with `type: :decorator`.\n\nIn a controller spec, you might want to check whether your instance variables\nare being decorated properly. You can use the handy predicate matchers:\n\n```ruby\nassigns(:article).should be_decorated\n\n# or, if you want to be more specific\nassigns(:article).should be_decorated_with ArticleDecorator\n```\n\nNote that `model.decorate == model`, so your existing specs shouldn't break when\nyou add the decoration.\n\n#### Spork Users\n\nIn your `Spork.prefork` block of `spec_helper.rb`, add this:\n\n```ruby\nrequire 'drape/test/rspec_integration'\n```\n\n### Isolated Tests\n\nIn tests, Drape needs to build a view context to access helper methods. By\ndefault, it will create an `ApplicationController` and then use its view\ncontext. If you are speeding up your test suite by testing each component in\nisolation, you can eliminate this dependency by putting the following in your\n`spec_helper` or similar:\n\n```ruby\nDrape::ViewContext.test_strategy :fast\n```\n\nIn doing so, your decorators will no longer have access to your application's\nhelpers. If you need to selectively include such helpers, you can pass a block:\n\n```ruby\nDrape::ViewContext.test_strategy :fast do\n  include ApplicationHelper\nend\n```\n\n#### Stubbing Route Helper Functions\n\nIf you are writing isolated tests for Drape methods that call route helper\nmethods, you can stub them instead of needing to require Rails.\n\nIf you are using RSpec, minitest-rails, or the Test::Unit syntax of minitest,\nyou already have access to the Drape `helpers` in your tests since they\ninherit from `Drape::TestCase`. If you are using minitest's spec syntax\nwithout minitest-rails, you can explicitly include the Drape `helpers`:\n\n```ruby\ndescribe YourDecorator do\n  include Drape::ViewHelpers\nend\n```\n\nThen you can stub the specific route helper functions you need using your\npreferred stubbing technique (this example uses RSpec's `stub` method):\n\n```ruby\nhelpers.stub(users_path: '/users')\n```\n\n## Advanced usage\n\n### Shared Decorator Methods\n\nYou might have several decorators that share similar needs. Since decorators are\njust Ruby objects, you can use any normal Ruby technique for sharing\nfunctionality.\n\nIn Rails controllers, common functionality is organized by having all\ncontrollers inherit from `ApplicationController`. You can apply this same\npattern to your decorators:\n\n```ruby\n# app/decorators/application_decorator.rb\nclass ApplicationDecorator \u003c Drape::Decorator\n# ...\nend\n```\n\nThen modify your decorators to inherit from that `ApplicationDecorator` instead\nof directly from `Drape::Decorator`:\n\n```ruby\nclass ArticleDecorator \u003c ApplicationDecorator\n  # decorator methods\nend\n```\n\n### Delegating Methods\n\nWhen your decorator calls `delegate_all`, any method called on the decorator not\ndefined in the decorator itself will be delegated to the decorated object. This\nis a very permissive interface.\n\nIf you want to strictly control which methods are called within views, you can\nchoose to only delegate certain methods from the decorator to the source model:\n\n```ruby\nclass ArticleDecorator \u003c Drape::Decorator\n  delegate :title, :body\nend\n```\n\nWe omit the `:to` argument here as it defaults to the `object` being decorated.\nYou could choose to delegate methods to other places like this:\n\n```ruby\nclass ArticleDecorator \u003c Drape::Decorator\n  delegate :title, :body\n  delegate :name, :title, to: :author, prefix: true\nend\n```\n\nFrom your view template, assuming `@article` is decorated, you could do any of\nthe following:\n\n```ruby\n@article.title # Returns the article's `.title`\n@article.body  # Returns the article's `.body`\n@article.author_name  # Returns the article's `author.name`\n@article.author_title # Returns the article's `author.title`\n```\n\n### Adding Context\n\nIf you need to pass extra data to your decorators, you can use a `context` hash.\nMethods that create decorators take it as an option, for example:\n\n```ruby\nArticle.first.decorate(context: {role: :admin})\n```\n\nThe value passed to the `:context` option is then available in the decorator\nthrough the `context` method.\n\nIf you use `decorates_association`, the context of the parent decorator is\npassed to the associated decorators. You can override this with the `:context`\noption:\n\n```ruby\nclass ArticleDecorator \u003c Drape::Decorator\n  decorates_association :author, context: {foo: \"bar\"}\nend\n```\n\nor, if you want to modify the parent's context, use a lambda that takes a hash\nand returns a new hash:\n\n```ruby\nclass ArticleDecorator \u003c Drape::Decorator\n  decorates_association :author,\n    context: -\u003e(parent_context){ parent_context.merge(foo: \"bar\") }\nend\n```\n\n### Specifying Decorators\n\nWhen you're using `decorates_association`, Drape uses the `decorate` method on\nthe associated record(s) to perform the decoration. If you want use a specific\ndecorator, you can use the `:with` option:\n\n```ruby\nclass ArticleDecorator \u003c Drape::Decorator\n  decorates_association :author, with: FancyPersonDecorator\nend\n```\n\nFor a collection association, you can specify a `CollectionDecorator` subclass,\nwhich is applied to the whole collection, or a singular `Decorator` subclass,\nwhich is applied to each item individually.\n\n### Scoping Associations\n\nIf you want your decorated association to be ordered, limited, or otherwise\nscoped, you can pass a `:scope` option to `decorates_association`, which will be\napplied to the collection *before* decoration:\n\n```ruby\nclass ArticleDecorator \u003c Drape::Decorator\n  decorates_association :comments, scope: :recent\nend\n```\n\n### Proxying Class Methods\n\nIf you want to proxy class methods to the wrapped model class, including when\nusing `decorates_finders`, Drape needs to know the model class. By default, it\nassumes that your decorators are named `SomeModelDecorator`, and then attempts\nto proxy unknown class methods to `SomeModel`.\n\nIf your model name can't be inferred from your decorator name in this way, you\nneed to use the `decorates` method:\n\n```ruby\nclass MySpecialArticleDecorator \u003c Drape::Decorator\n  decorates :article\nend\n```\n\nThis is only necessary when proxying class methods.\n\n### Making Models Decoratable\n\nModels get their `decorate` method from the `Drape::Decoratable` module, which\nis included in `ActiveRecord::Base` and `Mongoid::Document` by default. If\nyou're [using another\nORM](https://github.com/drapegem/drape/wiki/Using-other-ORMs) (including\nversions of Mongoid prior to 3.0), or want to decorate plain old Ruby objects,\nyou can include this module manually.\n\n## Contributors\n\nDrape was conceived by Jeff Casimir and heavily refined by Steve Klabnik and a\ngreat community of open source\n[contributors](https://github.com/drapegem/drape/contributors).\n\n### Core Team\n\n* Andrew Emelianenko (andrew@soften-it.com)\n* Jeff Casimir (jeff@jumpstartlab.com)\n* Steve Klabnik (steve@jumpstartlab.com)\n* Vasiliy Ermolovich\n* Andrew Haines\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fakodkod%2Fdrape","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fakodkod%2Fdrape","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fakodkod%2Fdrape/lists"}