Module: Hashie::Extensions::Dash::PropertyTranslation

Included in:
Trash
Defined in:
lib/hashie/extensions/dash/property_translation.rb

Overview

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 #=> Integer (Fixnum if you are using Ruby 2.3 or lower) model.created_at.class #=> Time

Defined Under Namespace

Modules: ClassMethods, InstanceMethods

Class Method Summary collapse

Class Method Details

.included(base) ⇒ Object


41
42
43
44
45
46
# 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, ::Hash.new { |hash, key| hash[key] = {} })
  base.extend(ClassMethods)
  base.send(:include, InstanceMethods)
end