Improve aliasing to object class name

This commit is contained in:
Andrew Haines 2013-05-20 11:16:34 +01:00
parent 9bd86b982a
commit a239d93288
2 changed files with 43 additions and 19 deletions

View File

@ -16,15 +16,6 @@ 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
@ -66,6 +57,7 @@ module Draper
# @return [void]
def self.decorates(object_class)
@object_class = object_class.to_s.camelize.constantize
alias_object_to_object_class_name
end
# Returns the source class corresponding to the decorator class, as set by
@ -228,6 +220,15 @@ module Draper
private
def self.inherited(subclass)
subclass.alias_object_to_object_class_name
super
end
def self.alias_object_to_object_class_name
alias_method object_class.name.underscore, :object if object_class?
end
def self.object_class_name
raise NameError if name.nil? || name.demodulize !~ /.+Decorator$/
name.chomp("Decorator")

View File

@ -361,20 +361,43 @@ 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"
describe "aliasing object to object class name" do
context "when object_class is inferrable from the decorator name" do
it "aliases object to the object class name" do
object = stub
decorator = ProductDecorator.new(object)
expect(decorator.product).to be object
end
end
it "aliases object to wrapped model name" do
decorator = ProductDecorator.new(Product.new)
context "when object_class is set by decorates" do
it "aliases object to the object class name" do
decorator_class = Class.new(Decorator) { decorates Product }
object = stub
decorator = decorator_class.new(object)
expect(decorator.product).not_to be nil
expect(decorator.product.name).to eq "bob"
expect(decorator.product).to be object
end
end
context "when object_class's name is several words long" do
it "underscores the method name" do
stub_const "LongWindedModel", Class.new
decorator_class = Class.new(Decorator) { decorates LongWindedModel }
object = stub
decorator = decorator_class.new(object)
expect(decorator.long_winded_model).to be object
end
end
context "when object_class is not set" do
it "does not alias object" do
decorator_class = Class.new(Decorator)
expect(decorator_class.instance_methods).to eq Decorator.instance_methods
end
end
end