From f5f27243c3f0c37bff4872e1e78521e570ff1e4f Mon Sep 17 00:00:00 2001 From: Sam-Serpoosh Date: Sun, 19 May 2013 13:01:36 -0500 Subject: [PATCH] Alias `object` to `#{model_name}` If we have an `ArticleDecorator` there is going to be a method added to it named `article` which is convenient for the user. --- lib/draper/decorator.rb | 9 +++++++++ spec/draper/decorator_spec.rb | 17 +++++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/lib/draper/decorator.rb b/lib/draper/decorator.rb index b2593c7..c2f256b 100755 --- a/lib/draper/decorator.rb +++ b/lib/draper/decorator.rb @@ -16,6 +16,15 @@ module Draper # @return [Hash] extra data to be used in user-defined methods. attr_accessor :context + def self.inherited(klass) + begin + alias_name = klass.name.downcase.gsub(/decorator/, "").to_sym + klass.send(:define_method, alias_name) do + object + end + rescue; end + end + # Wraps an object in a new instance of the decorator. # # Decorators may be applied to other decorators. However, applying a diff --git a/spec/draper/decorator_spec.rb b/spec/draper/decorator_spec.rb index 329c2f4..b5ff6a0 100755 --- a/spec/draper/decorator_spec.rb +++ b/spec/draper/decorator_spec.rb @@ -361,6 +361,23 @@ module Draper end end + describe "aliasing object to wrapped model name" do + class ::ProductDecorator < Decorator; end + class ::Product + attr_reader :name + def initialize + @name = "bob" + end + end + + it "aliases object to wrapped model name" do + decorator = ProductDecorator.new(Product.new) + + expect(decorator.product).not_to be nil + expect(decorator.product.name).to eq "bob" + end + end + describe "#to_model" do it "returns the decorator" do decorator = Decorator.new(Model.new)