Class: Hashie::Trash

Inherits:
Dash show all
Defined in:
lib/hashie/trash.rb

Overview

A Trash is a 'translated' Dash where the keys can be remapped from a source hash.

Trashes are useful when you need to read data from another application, such as a Java api, where the keys are named differently from how we would in Ruby.

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Dash

#[], inherited, #initialize, property?, #replace, required?

Methods included from PrettyInspect

#hashie_inspect, included

Methods inherited from Hash

#to_hash, #to_json

Methods included from HashExtensions

#hashie_stringify_keys, #hashie_stringify_keys!, included, #to_mash

Constructor Details

This class inherits a constructor from Hashie::Dash

Class Method Details

.property(property_name, options = {}) ⇒ Object

Defines a property on the Trash. Options are as follows:

  • :default - Specify a default value for this property, to be returned before a value is set on the property in a new Dash.
  • :from - Specify the original key name that will be write only.
  • :with - Specify a lambda to be used to convert value.
  • :transform_with - Specify a lambda to be used to convert value without using the :from option. It transform the property itself.

20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/hashie/trash.rb', line 20

def self.property(property_name, options = {})
  super

  if options[:from]
    if property_name.to_sym == options[:from].to_sym
      raise ArgumentError, "Property name (#{property_name}) and :from option must not be the same"
    end
    translations << options[:from].to_sym
    if options[:with].respond_to? :call
      class_eval do
        define_method "#{options[:from]}=" do |val|
          self[property_name.to_sym] = options[:with].call(val)
        end
      end
    else
      class_eval "def \#{options[:from]}=(val)\nself[:\#{property_name}] = val\nend\n"
    end
  elsif options[:transform_with].respond_to? :call
    transforms[property_name.to_sym] = options[:transform_with]
  end
end

Instance Method Details

#[]=(property, value) ⇒ Object

Set a value on the Dash in a Hash-like way. Only works on pre-existing properties.


48
49
50
51
52
53
54
55
56
# File 'lib/hashie/trash.rb', line 48

def []=(property, value)
  if self.class.translations.include? property.to_sym
    send("#{property}=", value)
  elsif self.class.transforms.key? property.to_sym
    super property, self.class.transforms[property.to_sym].call(value)
  elsif property_exists? property
    super
  end
end