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 from inconsistent APIs

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 using translation lambdas

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          #=> Fixnum
model.created_at.class  #=> Time

Public Class Methods

included(base) click to toggle source
# File lib/hashie/extensions/dash/property_translation.rb, line 41
def self.included(base)
  base.instance_variable_set(:@transforms, {})
  base.instance_variable_set(:@translations_hash, {})
  base.extend(ClassMethods)
  base.send(:include, InstanceMethods)
end