Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Payload map

  • Loading branch information...
commit eecbdcccc88207afd2faf9b2f7ba0cce23eadc47 1 parent c062776
DanielVartanov authored
Showing with 81 additions and 0 deletions.
  1. +44 −0 lib/payload_map.rb
  2. +37 −0 test/unit/payload_map_spec.rb
View
44 lib/payload_map.rb
@@ -0,0 +1,44 @@
+module SData
+ module PayloadMap
+ def define_payload_map(map)
+ cattr_accessor :payload_map
+ cattr_accessor :payload
+
+ self.payload_map = map
+ self.payload = payload_fields_proxy
+ end
+
+ protected
+
+ module PayloadFieldsProxy
+ module ClassMethods
+ def define_readers(readers)
+ readers.each { |reader| attr_reader reader }
+ end
+ end
+
+ module InstanceMethods
+ def set_values(values)
+ values.each_pair do |key, value|
+ ivar_sym = "@#{key.to_s}".to_sym
+ instance_variable_set ivar_sym, value
+ end
+ end
+ end
+ end
+
+ def payload_fields_proxy
+ proxy_class = Class.new
+ proxy_class.extend PayloadFieldsProxy::ClassMethods
+ proxy_class.__send__ :include, PayloadFieldsProxy::InstanceMethods
+ proxy_class.define_readers(self.payload_map.keys)
+
+ returning proxy_class.new do |proxy|
+ field_values = self.payload_map.merge(self.payload_map) { |key, value| value[:static_value] }
+ proxy.set_values(field_values)
+ end
+ end
+ end
+end
+
+VirtualBase.extend SData::PayloadMap
View
37 test/unit/payload_map_spec.rb
@@ -0,0 +1,37 @@
+require File.join(File.dirname(__FILE__), 'spec_helper')
+
+describe SData::PayloadMap do
+ context "given a VirtualBase class extended by SData::PayloadMap" do
+ before :all do
+ VirtualBase.extend SData::PayloadMap
+ end
+
+ it "should respond to #payload_map class method" do
+ VirtualBase.should respond_to(:define_payload_map)
+ end
+
+ describe "#define_payload_map" do
+ context "when mapping leads to static value" do
+ before :all do
+ VirtualBase.define_payload_map :tax_reference => { :static_value => 'Some static tax reference' }
+ end
+
+ subject { VirtualBase.new(Object) }
+
+ it { should respond_to(:payload) }
+
+ context "when correspondent field method is called" do
+ it "should return given static value" do
+ subject.payload.tax_reference.should == 'Some static tax reference'
+ end
+ end
+
+ describe "#payload_map" do
+ subject { VirtualBase.new(Object).payload_map }
+
+ it { should == { :tax_reference => { :static_value => 'Some static tax reference' } } }
+ end
+ end
+ end
+ end
+end
Please sign in to comment.
Something went wrong with that request. Please try again.