Class: Hashie::Twash

Inherits:
Dash
  • Object
show all
Defined in:
lib/hashie/twash.rb

Overview

A Twash is a two-way Trash. You can get back to the original keys using #to_hash

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

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

Defines a property on the Twash. 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.



12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/hashie/twash.rb', line 12

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

  if options[:from]
    translations[options[:from].to_sym] = property_name.to_sym
    class_eval <<-RUBY
      def #{options[:from]}=(val)
        self[:#{property_name}] = val
      end
    RUBY
  end
end

Instance Method Details

#[]=(property, value) ⇒ Object

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



27
28
29
30
31
32
33
# File 'lib/hashie/twash.rb', line 27

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

#to_hashObject



35
36
37
38
39
40
41
42
43
44
# File 'lib/hashie/twash.rb', line 35

def to_hash
  out = super
  self.class.translations.each do |from, to|
    to_s = to.to_s
    if out.keys.include?(to_s)
      out[from.to_s] = out.delete(to_s)
    end
  end
  out
end