Sha256: 266f7e0e3be0e34fe62ee9874513d712a98542a0dfe69b4fe3c772cba669c790

Contents?: true

Size: 1.52 KB

Versions: 6

Compression:

Stored size: 1.52 KB

Contents

module Exchanger
  module Attributes
    def attributes=(values = {})
      values.each do |name, value|
        write_attribute(name, value)
      end
    end

    # Return the attributes hash with indifferent access.
    def attributes
      @attributes.with_indifferent_access
    end

    # TODO: Add typecasting
    # Read a value from the +Document+ attributes. If the value does not exist
    # it will return nil.
    def read_attribute(name)
      name = name.to_s
      value = @attributes[name]
      accessed(name, value)
    end

    # TODO: Add typecasting
    def write_attribute(name, value)
      name = name.to_s
      modify(name, @attributes[name], value)
    end

    def identifier
      if self.class.identifier_name
        @identifier ||= self.send(self.class.identifier_name)
        @identifier.tag_name = self.class.identifier_name.to_s.camelize if @identifier
        @identifier
      end
    end

    def id
      identifier && identifier.id
    end

    def change_key
      identifier && identifier.change_key
    end

    # Override respond_to? so it responds properly for dynamic attributes
    def respond_to?(name)
      (@attributes && @attributes.has_key?(name.to_s)) || super
    end

    # Used for allowing accessor methods for dynamic attributes
    def method_missing(name, *args)
      attr = name.to_s.sub("=", "")
      return super unless attributes.has_key?(attr)
      if name.to_s.ends_with?("=")
        write_attribute(attr, *args)
      else
        read_attribute(attr)
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
exchanger-0.1.5 lib/exchanger/attributes.rb
exchanger-0.1.4 lib/exchanger/attributes.rb
exchanger-0.1.3 lib/exchanger/attributes.rb
exchanger-0.1.2 lib/exchanger/attributes.rb
exchanger-0.1.1 lib/exchanger/attributes.rb
exchanger-0.1.0 lib/exchanger/attributes.rb