Sha256: 4827d06af0f21410e6317efe36676b8c248b311dcebffd4a57240b15872bf098

Contents?: true

Size: 1.15 KB

Versions: 2

Compression:

Stored size: 1.15 KB

Contents

module Securetrading
  class BaseModel
    attr_reader :attributes_hash

    def initialize(attrs_hash = {})
      @attributes_hash = attrs_hash.presence &&
                         attrs_hash.transform_keys! { |k| k.to_s.tr('__', '') }
    end

    def ox_xml
      ox = ox_from_values
      sub_classes.each do |sub_class_name|
        next unless attributes_hash.key?(sub_class_name)
        ox << send(sub_class_name).ox_xml
      end
      ox
    end

    private

    def ox_from_values
      XmlDoc
        .elements(xml_tag_name => @attributes_hash.except(*sub_classes))
        .first
    end

    def xml_tag_name
      self.class.name.demodulize.downcase
    end

    def method_missing(m, *args, &block)
      return super unless attributes_hash.key?(m.to_s)
      determine_value(m.to_s)
    end

    def determine_value(name)
      if name == 'error'
        Securetrading::ResponseError.new(attributes_hash[name])
      elsif name.in?(sub_classes)
        "Securetrading::#{name.capitalize}".constantize
          .public_send(:new, attributes_hash[name])
      else
        attributes_hash[name]
      end
    end

    def sub_classes
      []
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
securetrading-0.4.0 lib/securetrading/base_model.rb
securetrading-0.3.2 lib/securetrading/base_model.rb