From 8fd23c52deb96772f73593cdb72e2f7c34c54f8b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marc=20Busqu=C3=A9?= Date: Wed, 2 Jan 2019 16:28:51 +0100 Subject: [PATCH] Map canonical names and aliases in a schema --- core/lib/rom/schema.rb | 11 +++++++++++ core/spec/unit/rom/schema_spec.rb | 9 +++++++++ 2 files changed, 20 insertions(+) diff --git a/core/lib/rom/schema.rb b/core/lib/rom/schema.rb index 65605bc2a..b888e8ba6 100644 --- a/core/lib/rom/schema.rb +++ b/core/lib/rom/schema.rb @@ -430,6 +430,17 @@ def to_ast [:schema, [name, attributes.map(&:to_ast)]] end + # Hash from canonical name to alias for aliased attributes + # + # @return [Hash] + # + # @api public + def alias_mapping + each_with_object({}) do |attr, obj| + obj[attr.name] = attr.alias if attr.aliased? + end + end + # @api private def set!(key, value) instance_variable_set("@#{ key }", value) diff --git a/core/spec/unit/rom/schema_spec.rb b/core/spec/unit/rom/schema_spec.rb index e94f03bf2..c6caf2666 100644 --- a/core/spec/unit/rom/schema_spec.rb +++ b/core/spec/unit/rom/schema_spec.rb @@ -54,4 +54,13 @@ expect(schema.project(:name).primary_key_name).to be(:id) end end + + describe '#alias_mapping' do + it 'returns a hash from canonical name to alias including aliased attributes' do + attrs = { id: ROM::Types::Integer.meta(name: :id, alias: :pk), name: ROM::Types::String } + schema = ROM::Schema.define(:name, attributes: attrs.values) + + expect(schema.alias_mapping).to eq(id: :pk) + end + end end