Skip to content

Instantly share code, notes, and snippets.

@catmando catmando/mapper.rb
Last active Sep 13, 2017

Embed
What would you like to do?
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
You can’t perform that action at this time.