1
0
Fork 0
mirror of https://github.com/drapergem/draper synced 2023-03-27 23:21:17 -04:00
draper/lib/draper.rb
Bruno Castro 6b3e9bc5c9 feat: Include ORM associations in CollectionDecorator (#845)
## Description
Include all QueryMethods from the ORM in CollectionDecorator. The default adapter is :active_record

* Why was this change required?
It was necessary to delegate or define a method of the ORM which you are using in your decorator to make an instance of CollectionDecorator able to call it.
* Is there something you aren't happy with or that needs extra attention?
In order to support other ORM associations, we'll need to write a method `allowed?` for each strategy at `lib/draper/query_methods/load_strategy.rb`

## Testing
1. Create a decorator for the model and its association
```ruby
class OrderHistoryDecorator < Draper::Decorator
  delegate_all
end

class OrderDecorator < Draper::Decorator
  delegate_all

  decorates_association :order_histories, with: OrderHistoryDecorator
end
```

2. Call any query method in the decorated instance
```ruby
pry(main)> Order.last.decorate.order_histories.includes(:user)
```

## References
* Issue #702 
* Issue #812
2019-02-25 10:44:19 -06:00

69 lines
1.8 KiB
Ruby

require 'action_view'
require 'active_model/naming'
require 'active_model/serialization'
require 'active_model/serializers/json'
require 'active_model/serializers/xml'
require 'active_support/inflector'
require 'active_support/core_ext/hash/keys'
require 'active_support/core_ext/hash/reverse_merge'
require 'active_support/core_ext/name_error'
require 'draper/version'
require 'draper/configuration'
require 'draper/view_helpers'
require 'draper/compatibility/api_only'
require 'draper/delegation'
require 'draper/automatic_delegation'
require 'draper/finders'
require 'draper/decorator'
require 'draper/helper_proxy'
require 'draper/lazy_helpers'
require 'draper/decoratable'
require 'draper/factory'
require 'draper/decorated_association'
require 'draper/helper_support'
require 'draper/view_context'
require 'draper/query_methods'
require 'draper/collection_decorator'
require 'draper/undecorate'
require 'draper/decorates_assigned'
require 'draper/railtie' if defined?(Rails)
module Draper
extend Draper::Configuration
def self.setup_action_controller(base)
base.class_eval do
include Draper::Compatibility::ApiOnly if base == ActionController::API
include Draper::ViewContext
extend Draper::HelperSupport
extend Draper::DecoratesAssigned
before_action :activate_draper
end
end
def self.setup_action_mailer(base)
base.class_eval do
include Draper::ViewContext
end
end
def self.setup_orm(base)
base.class_eval do
include Draper::Decoratable
end
end
class UninferrableDecoratorError < NameError
def initialize(klass)
super("Could not infer a decorator for #{klass}.")
end
end
class UninferrableObjectError < NameError
def initialize(klass)
super("Could not infer an object for #{klass}.")
end
end
end