Module: DecentExposure::Draper::ClassMethods

Defined in:
lib/decent_exposure-draper.rb

Instance Method Summary collapse

Instance Method Details

#expose(name, decorator = nil, &block) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/decent_exposure-draper.rb', line 13

def expose(name, decorator = nil, &block)
  if block_given?
    super(name, &block)
  else
    super(name, &default_exposure)
  end
  
  super_method = instance_method(name)
  
  define_method(name) do
    model_or_collection = super_method.bind(self).call
    
    if model_or_collection.nil? or model_or_collection.is_a?(::Draper::Base)
      model_or_collection
    else
      begin
        unless decorator.present?
          klass = model_or_collection.respond_to?(:scoped) ? model_or_collection.first.class : model_or_collection.class
          decorator = "#{klass.to_s.classify}Decorator".constantize
        end
        decorator.decorate(model_or_collection)
      rescue NameError
        model_or_collection
      end
    end
  end
end