module Hashie::Extensions::Dash::PropertyTranslation::InstanceMethods

Applies translations and transformations during assignment.

@example

klass = Class.new(Hashie::Dash) do
  include Hashie::Extensions::Dash::PropertyTranslation
  property :name, from: :fullName
end
klass.new(fullName: 'Ada').name # => 'Ada'

Public Instance Methods

[]=(property, value) click to toggle source

Sets a value on the Dash in a Hash-like way.

Note: Only works on pre-existing properties.

@example Assign through a translated source key

klass = Class.new(Hashie::Dash) do
  include Hashie::Extensions::Dash::PropertyTranslation
  property :name, from: :fullName
end
dash = klass.new
dash[:fullName] = 'Ada'
dash.name # => 'Ada'
Calls superclass method
# File lib/hashie/extensions/dash/property_translation.rb, line 250
def []=(property, value)
  if self.class.translation_exists? property
    send("#{property}=", value)

    if self.class.transformation_exists? property
      super(property, self.class.transformed_property(property, value))
    elsif self.class.properties.include?(property)
      super
    end
  elsif self.class.transformation_exists? property
    super(property, self.class.transformed_property(property, value))
  elsif property_exists? property
    super
  end
end
initialize_attributes(attributes) click to toggle source

Deletes any keys that have a translation

@example Initialize translated input without modifying the source

klass = Class.new(Hashie::Dash) do
  include Hashie::Extensions::Dash::PropertyTranslation
  property :name, from: :fullName
end
attributes = {fullName: 'Ada'}
dash = klass.new
dash.initialize_attributes(attributes)
dash.name # => 'Ada'
attributes # => {fullName: 'Ada'}
Calls superclass method
# File lib/hashie/extensions/dash/property_translation.rb, line 278
def initialize_attributes(attributes)
  return unless attributes

  attributes_copy = attributes.dup.delete_if do |k, v|
    if self.class.translations_hash.include?(k)
      self[k] = v
      true
    end
  end
  super(attributes_copy)
end
property_exists?(property) click to toggle source

Raises an NoMethodError if the property doesn't exist

@example Check for an existing property

klass = Class.new(Hashie::Dash) do
  include Hashie::Extensions::Dash::PropertyTranslation
  property :name
end
dash = klass.new
dash.property_exists?(:name) # => true
expect { dash.property_exists?(:missing) }.to raise_error(NoMethodError)
# File lib/hashie/extensions/dash/property_translation.rb, line 300
def property_exists?(property)
  fail_no_property_error!(property) unless self.class.property?(property)
  true
end

Private Instance Methods

__translations() click to toggle source
# File lib/hashie/extensions/dash/property_translation.rb, line 307
def __translations
  self.class.translations_hash
end