Skip to content

Commit

Permalink
Add Pragma::Decorator::Association::Expander from pragma
Browse files Browse the repository at this point in the history
  • Loading branch information
aldesantis committed Feb 1, 2020
1 parent ca94bd8 commit 45dff1b
Show file tree
Hide file tree
Showing 5 changed files with 107 additions and 0 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Expand Up @@ -11,6 +11,8 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.

- Added `Pragma::Decorator::Error`, which was previously in
[pragma](https://github.com/pragmarb/pragma)
- Added `Pragma::Decorator::Association::Expander`, which was previously in
[pragma](https://github.com/pragmarb/pragma)

### Changed

Expand Down
12 changes: 12 additions & 0 deletions lib/pragma/decorator/association/expander.rb
@@ -0,0 +1,12 @@
# frozen_string_literal: true

module Pragma
module Decorator
module Association
module Expander
include Adaptor::Loader
register ActiveRecord, Poro
end
end
end
end
45 changes: 45 additions & 0 deletions lib/pragma/decorator/association/expander/active_record.rb
@@ -0,0 +1,45 @@
# frozen_string_literal: true

module Pragma
module Decorator
module Association
module Expander
class ActiveRecord < Base
class << self
def supports?(relation)
defined?(::ActiveRecord::Relation) && relation.is_a?(::ActiveRecord::Relation)
end
end

def include_associations(expands)
relation.includes(validate_associations(
relation.model,
destruct_associations(expands)
))
end

private

def destruct_associations(expands)
associations = {}

expands.each do |expand|
expand.split('.').inject(associations) do |accumulator, association|
accumulator[association] ||= {}
end
end

associations
end

def validate_associations(model, associations)
Hash[associations.map do |(key, value)|
reflection = model.reflect_on_association(key.to_sym)
reflection ? [key, validate_associations(reflection.klass, value)] : [false, false]
end.select { |_, v| v }]
end
end
end
end
end
end
27 changes: 27 additions & 0 deletions lib/pragma/decorator/association/expander/base.rb
@@ -0,0 +1,27 @@
# frozen_string_literal: true

module Pragma
module Decorator
module Association
module Expander
class Base
attr_reader :relation

class << self
def supports?(_relation)
fail NotImplementedError
end
end

def initialize(relation)
@relation = relation
end

def include_associations(_expands)
fail NotImplementedError
end
end
end
end
end
end
21 changes: 21 additions & 0 deletions lib/pragma/decorator/association/expander/poro.rb
@@ -0,0 +1,21 @@
# frozen_string_literal: true

module Pragma
module Decorator
module Association
module Expander
class Poro < Base
class << self
def supports?(_relation)
true
end
end

def include_associations(_expands)
relation
end
end
end
end
end
end

0 comments on commit 45dff1b

Please sign in to comment.