Skip to content

Instantly share code, notes, and snippets.

@catmando
Last active September 13, 2017 21:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save catmando/1f200bb6128a555c7ded6ae55df269d0 to your computer and use it in GitHub Desktop.
Save catmando/1f200bb6128a555c7ded6ae55df269d0 to your computer and use it in GitHub Desktop.
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