Let’s say I have a model called Article:
class Article < ActiveRecord::Base
end
And then I have a class that is intended to add behavior to an article object (a decorator):
class ArticleDecorator
def format_title
end
end
If I wanted to extend behavior of an article object, I could make ArticleDecorator a module and then call article.extend(ArticleDecorator), but I’d prefer something like this:
article = ArticleDecorator.decorate(Article.top_articles.first) # for single object
or
articles = ArticleDecorator.decorate(Article.all) # for collection of objects
How would I go about implementing this decorate method?
What exactly do you want from
decoratemethod? Should it simply add some new methods to passed objects or it should automatically wrap methods of these objects with corresponding format methods? And why do you wantArticleDecoratorto be a class and not just a module?Updated:
Seems like solution from nathanvda is what you need, but I’d suggest a bit cleaner version:
It does the same thing, but:
Kernel#Arraymethod.Object#extenddirectly (it’s a public method so there’s no need in invoking it throughsend).Object#extendincludes only instance methods so we can put them right inArticleDecoratorwithout wrapping them with another module.