Module: Samurai::ActiveResourceSupport

Included in:
PaymentMethod, Transaction
Defined in:
lib/samurai/active_resource_support.rb

Class Method Summary collapse

Class Method Details

.included(base) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/samurai/active_resource_support.rb', line 4

def self.included(base)
  if [ActiveResource::VERSION::MAJOR, ActiveResource::VERSION::MINOR].compact.join('.').to_f < 3.0
    # If we're using ActiveResource pre-3.1, there's no schema class method, so we resort to some tricks...
    # Initialize the known attributes from the schema as empty strings, so that they can be accessed via method-missing
    base.const_set 'EMPTY_ATTRIBUTES', base.const_get('KNOWN_ATTRIBUTES').inject(HashWithIndifferentAccess.new) {|h, k| h[k] = ''; h}

    base.class_eval do
      # Modify the constructor to emulate the schema behavior
      def initialize(attrs={})
        _empty_attributes = self.class.const_get('EMPTY_ATTRIBUTES')
        super(_empty_attributes.merge(attrs))
      end

      # Add missing #update_attributes
      def update_attributes(attributes)
        load(attributes) && save
      end
    end

  else
    # Post AR 3.1, we can use the schema method to define our attributes
    base.schema { string *base.const_get('KNOWN_ATTRIBUTES') }
  end
end