Sha256: f06edf038613ef5f3fad847f3dcdee8d15690df0d26126c3efbe031ea7f492fe

Contents?: true

Size: 1.52 KB

Versions: 16

Compression:

Stored size: 1.52 KB

Contents

require 'hashie/dash'

module Hashie
  # 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 < Hashie::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

16 entries across 16 versions & 5 rubygems

Version Path
fragrant-0.0.5 vendor/bundle/ruby/1.9.1/gems/hashie-1.2.0/lib/hashie/trash.rb
cb_hashie-2.0.0.beta lib/hashie/trash.rb
hashie-model-1.2.3 vendor/hashie/lib/hashie/trash.rb
hashie-model-1.2.1 vendor/hashie/lib/hashie/trash.rb
hashie-model-1.2.0 vendor/hashie/lib/hashie/trash.rb
hashie-model-1.1.0 vendor/hashie/lib/hashie/trash.rb
hashie-model-1.0.1 vendor/hashie/lib/hashie/trash.rb
hashie-model-1.0.0.alpha vendor/hashie/lib/hashie/trash.rb
hashie-1.2.0 lib/hashie/trash.rb
hashie-1.1.0 lib/hashie/trash.rb
hashie-1.0.0 lib/hashie/trash.rb
putio-0.0.1.pre2 development/ruby/1.8/gems/hashie-0.4.0/lib/hashie/trash.rb
putio-0.0.1.pre development/ruby/1.8/gems/hashie-0.4.0/lib/hashie/trash.rb
hashie-0.4.0 lib/hashie/trash.rb
hashie-0.3.1 lib/hashie/trash.rb
hashie-0.3.0 lib/hashie/trash.rb