Last active
September 13, 2017 21:17
-
-
Save catmando/1f200bb6128a555c7ded6ae55df269d0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Something | |
def self.display_map | |
[ | |
{ | |
key: :position, | |
name: 'Number' | |
}, | |
{ | |
key: :design_collection, | |
name: 'Collection', | |
relation: true, | |
columns: [:name, :id] | |
}, | |
{ | |
key: :design_style_details, | |
relation: true, | |
columns: [:id] | |
} | |
] | |
end | |
end | |
class Mapper | |
def initialize(klass, scope: nil) | |
@klass = klass | |
@scope = scope&.to_sym || :all | |
end | |
def map_items | |
@klass.send(@scope).map do |record| | |
@klass.display_map.inject({obj: record}) do |hash, att| | |
data = record.send(attr[:key]) | |
if (reflection = @klass.reflect_on_association(attr[:key])) | |
if reflection.collection? | |
data = data.map { |r| r.slice(att[:columns]) } | |
else | |
data = data.slice(att[:columns]) | |
end | |
end | |
hash.update(attr[:key] => { data: data, name: att[:name] }) | |
end | |
end | |
end | |
end | |
# and slice is implemented on client so here it is: (see https://github.com/ruby-hyperloop/hyper-mesh/issues/36) | |
module ActiveRecord | |
module InstanceMethods | |
def slice(methods) | |
Hash[methods.map { |method| [method, send(method)] }] | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment