{"id":22792666,"url":"https://github.com/johnantoni/rails_decorators","last_synced_at":"2025-03-30T17:17:43.496Z","repository":{"id":66484241,"uuid":"1869048","full_name":"johnantoni/rails_decorators","owner":"johnantoni","description":"Implementation of the decorator pattern for object-oriented data formatting in Rails applications","archived":false,"fork":false,"pushed_at":"2011-06-01T19:52:30.000Z","size":769,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-02-05T19:08:49.789Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"Ruby","has_issues":false,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/johnantoni.png","metadata":{"files":{"readme":"README.markdown","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2011-06-09T03:39:26.000Z","updated_at":"2015-03-27T05:45:21.000Z","dependencies_parsed_at":"2023-02-20T05:00:34.540Z","dependency_job_id":null,"html_url":"https://github.com/johnantoni/rails_decorators","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/johnantoni%2Frails_decorators","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/johnantoni%2Frails_decorators/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/johnantoni%2Frails_decorators/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/johnantoni%2Frails_decorators/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/johnantoni","download_url":"https://codeload.github.com/johnantoni/rails_decorators/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":246351016,"owners_count":20763232,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","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":[],"created_at":"2024-12-12T03:15:43.908Z","updated_at":"2025-03-30T17:17:43.463Z","avatar_url":"https://github.com/johnantoni.png","language":"Ruby","funding_links":[],"categories":[],"sub_categories":[],"readme":"Rails Decorators\n================\n\nThis gem makes it easy to apply the decorator pattern to the models in a Rails application.\n\n## Why use decorators?\n\nHelpers, as they're commonly used, are a bit odd. In both Ruby and Rails we approach everything from an Object-Oriented perspective, then with helpers we get procedural.\n\nThe job of a helper is to take in data or a data object and output presentation-ready results. We can do that job in an OO fashion with a decorator.\n\nIn general, a decorator wraps an object with presentation-related accessor methods. For instance, if you had an `Article` object, then a decorator might add instance methods like `.formatted_published_at` or `.formatted_title` that output actual HTML.\n\n## How is it implemented?\n\nTo implement the pattern in Rails we can:\n\n1. Write a wrapper class with the decoration methods\n2. Wrap the data object\n3. Utilize those methods within our view layer\n\n## How do you utilize this gem in your application?\n\nHere are the steps to utilizing this gem:\n\nAdd the dependency to your `Gemfile`:\n\n```\ngem \"rails_decorators\"\n```\n\nRun bundle:\n\n```\nbundle\n```\n\nCreate a decorator for your model (ex: `Article`)\n\n```\nrails generate decorator:model Article\n```\n\nOpen the decorator model (ex: `app/decorators/article_decorator.rb`)\n\nAdd your new formatting methods as normal instance or class methods. You have access to the Rails helpers from the following classes:\n\n```\nActionView::Helpers::TagHelper\nActionView::Helpers::UrlHelper\nActionView::Helpers::TextHelper\n```\n\nUse the new methods in your views like any other model method (ex: `@article.formatted_published_at`)\n\n## Possible Decoration Methods\n\nHere are some ideas of what you might do in decorator methods:\n\n* Implement output formatting for `to_csv`, `to_json`, or `to_xml`\n* Format dates and times using `strftime`\n* Implement a commonly used representation of the data object like a `.name` method that combines `first_name` and `last_name` attributes\n\n## Example Using a Decorator\n\nSay I have a publishing system with `Article` resources. My designer decides that whenever we print the `published_at` timestamp, it should be constructed like this:\n\n```html\n\u003cspan class='published_at'\u003e\n  \u003cspan class='date'\u003eMonday, May 6\u003c/span\u003e\n  \u003cspan class='time'\u003e8:52AM\u003c/span\u003e\n\u003c/span\u003e\n```\n\nCould we build that using a partial? Yes. A helper? Uh-huh. But the point of the decorator is to encapsulate logic just like we would a method in our models. Here's how to implement it.\n\nFirst, follow the steps above to add the dependency, update your bundle, then run the `rails generate decorator:setup` to prepare your app.\n\nSince we're talking about the `Article` model we'll create an `ArticleDecorator` class. You could do it by hand, but use the provided generator:\n\n```\nrails generate decorator:model Article\n```\n\nNow open up the created `app/decorators/article_decorator.rb` and you'll find an `ArticleDecorator` class. You'll see commented-out samples for how to utilize Rails' view helper methods. Move below those comments and add this method:\n\n```ruby\ndef formatted_published_at\n  date = content_tag(:span, published_at.strftime(\"%A, %B %e\").squeeze(\" \"), :class =\u003e 'date')\n  time = content_tag(:span, published_at.strftime(\"%l:%M%p\").delete(\" \"), :class =\u003e 'time')\n  content_tag :span, date + time, :class =\u003e 'published_at'\nend\n```\n\n*ASIDE*: Unfortunately, due to the current implementation of `content_tag`, you can't use the style of sending the content is as a block or you'll get an error about `undefined method 'output_buffer='`. Passing in the content as the second argument, as above, works fine.\n\nThen you need to perform the wrapping in your controller. Here's the simplest method:\n\n```ruby\nclass ArticlesController \u003c ApplicationController\n  def show\n    @article = ArticleDecorator.new( Article.find params[:id] )\n  end\nend\n```\n\nThen within your views you can utilize both the normal data methods and your new presentation methods:\n\n```ruby\n\u003c%= @article.formatted_published_at %\u003e\n```\n\nTa-da! Object-oriented data formatting for your view layer. Below is the complete decorator with extra comments removed:\n\n```ruby\nclass ArticleDecorator \u003c RailsDecorators::Base\n  def formatted_published_at\n    date = content_tag(:span, published_at.strftime(\"%A, %B %e\").squeeze(\" \"), :class =\u003e 'date')\n    time = content_tag(:span, published_at.strftime(\"%l:%M%p\"), :class =\u003e 'time').delete(\" \")\n    content_tag :span, date + time, :class =\u003e 'created_at'\n  end\nend\n```\n\n## License\n\n(The MIT License)\n\nCopyright © 2011 Jeff Casimir\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ‘Software’), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED ‘AS IS’, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjohnantoni%2Frails_decorators","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fjohnantoni%2Frails_decorators","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjohnantoni%2Frails_decorators/lists"}