module Hashie::Extensions::Dash::PropertyTranslation

Extends a Dash with the ability to remap keys from a source hash.

Property translation is useful when you need to read data from another application – such as a Java API – where the keys are named differently from Ruby conventions.

@example Translate inconsistent API keys

class PersonHash < Hashie::Dash
  include Hashie::Extensions::Dash::PropertyTranslation

  property :first_name, from: :firstName
  property :last_name, from: :lastName
  property :first_name, from: :f_name
  property :last_name, from: :l_name
end

person = PersonHash.new(firstName: 'Michael', l_name: 'Bleigh')
person[:first_name]  #=> 'Michael'
person[:last_name]   #=> 'Bleigh'

You can also use a lambda to translate the value. This is particularly useful when you want to ensure the type of data you're wrapping.

@example Transform input values

require 'time'

class DataModelHash < Hashie::Dash
  include Hashie::Extensions::Dash::PropertyTranslation

  property :id, transform_with: ->(value) { value.to_i }
  property :created_at, from: :created, with: ->(value) { Time.parse(value) }
end

model = DataModelHash.new(id: '123', created: '2014-04-25 22:35:28')
model.id.class          #=> Integer
model.created_at.class  #=> Time

Public Class Methods

included(base) click to toggle source

@example Install translation declarations on a Dash

klass = Class.new(Hashie::Dash) do
  include Hashie::Extensions::Dash::PropertyTranslation
  property :name, from: :fullName
end
klass.new(fullName: 'Ada').name # => 'Ada'
# File lib/hashie/extensions/dash/property_translation.rb, line 50
def self.included(base)
  base.instance_variable_set(:@transforms, {})
  base.instance_variable_set(:@translations_hash, ::Hash.new { |hash, key| hash[key] = {} })
  base.extend(ClassMethods)
  base.send(:include, InstanceMethods)
  base.extend Hashie::Extensions::DeepMerge
end