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