Sha256: 39af31dba4c29ae7f81937a802b733e3cb0c24a74818d3c4bbd4871f377c7639

Contents?: true

Size: 1.52 KB

Versions: 13

Compression:

Stored size: 1.52 KB

Contents

require 'hashie2/dash'

module Hashie2
  # 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 Trash < Hashie2::Dash

    # Defines a property on the Trash. Options are as follows:
    #
    # * <tt>:default</tt> - Specify a default value for this property, to be
    # returned before a value is set on the property in a new Dash.
    # * <tt>:from</tt> - Specify the original key name that will be write only.
    def self.property(property_name, options = {})
      super

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

    # Set a value on the Dash in a Hash-like way. Only works
    # on pre-existing properties.
    def []=(property, value)
      if self.class.translations.include? property.to_sym
        send("#{property}=", value)
      elsif property_exists? property
        super
      end
    end

    private

    def self.translations
      @translations ||= []
    end

    # Raises an NoMethodError if the property doesn't exist
    #
    def property_exists?(property)
      unless self.class.property?(property.to_sym)
        raise NoMethodError, "The property '#{property}' is not defined for this Trash."
      end
      true
    end
  end
end

Version data entries

13 entries across 13 versions & 1 rubygems

Version Path
hashie-model-1.4.2 vendor/hashie2/lib/hashie2/trash.rb
hashie-model-1.4.1 vendor/hashie2/lib/hashie2/trash.rb
hashie-model-1.4.0 vendor/hashie2/lib/hashie2/trash.rb
hashie-model-1.3.9 vendor/hashie2/lib/hashie2/trash.rb
hashie-model-1.3.8 vendor/hashie2/lib/hashie2/trash.rb
hashie-model-1.3.7 vendor/hashie2/lib/hashie2/trash.rb
hashie-model-1.3.6 vendor/hashie2/lib/hashie2/trash.rb
hashie-model-1.3.5 vendor/hashie2/lib/hashie2/trash.rb
hashie-model-1.3.4 vendor/hashie2/lib/hashie2/trash.rb
hashie-model-1.3.3 vendor/hashie2/lib/hashie2/trash.rb
hashie-model-1.3.2 vendor/hashie2/lib/hashie2/trash.rb
hashie-model-1.3.1 vendor/hashie2/lib/hashie2/trash.rb
hashie-model-1.3.0 vendor/hashie2/lib/hashie2/trash.rb