Sha256: 9374d0279d5ff588b37e3773ac462a3a6f2896bb2a9f845033422bfc50956919

Contents?: true

Size: 1.29 KB

Versions: 18

Compression:

Stored size: 1.29 KB

Contents

module Flexirest
  module Associations
    module ClassMethods
      include ActiveSupport::Inflector

      def has_many(key, klass = nil)
        if klass.nil?
          klass = key.to_s.classify.constantize
        end

        @_associations ||= {}
        @_associations[key] = klass
        define_method(key) do
          unless _attributes[key].is_a?(Array) || _attributes[key].is_a?(Flexirest::ResultIterator)
            return _attributes[key]
          end

          if _attributes[key].size == 0
            return _attributes[key]
          end

          if _attributes[key][0].is_a?(klass)
            return _attributes[key]
          end

          _attributes[key].each_with_index do |v, k|
            _attributes[key][k] = klass.new(v)
          end

          _attributes[key]
        end
      end

      def has_one(key, klass = nil)
        if klass.nil?
          klass = key.to_s.classify.constantize
        end

        @_associations ||= {}
        @_associations[key] = klass
        define_method(key) do
          if _attributes[key].is_a?(klass)
            return _attributes[key]
          end

          _attributes[key] = klass.new(_attributes[key])

          _attributes[key]
        end
      end
    end

    def self.included(base)
      base.extend(ClassMethods)
    end
  end
end

Version data entries

18 entries across 18 versions & 1 rubygems

Version Path
flexirest-1.3.19 lib/flexirest/associations.rb
flexirest-1.3.18 lib/flexirest/associations.rb
flexirest-1.3.17 lib/flexirest/associations.rb
flexirest-1.3.16 lib/flexirest/associations.rb
flexirest-1.3.15 lib/flexirest/associations.rb
flexirest-1.3.14 lib/flexirest/associations.rb
flexirest-1.3.13 lib/flexirest/associations.rb
flexirest-1.3.12 lib/flexirest/associations.rb
flexirest-1.3.10 lib/flexirest/associations.rb
flexirest-1.3.9 lib/flexirest/associations.rb
flexirest-1.3.8 lib/flexirest/associations.rb
flexirest-1.3.7 lib/flexirest/associations.rb
flexirest-1.3.6 lib/flexirest/associations.rb
flexirest-1.3.5 lib/flexirest/associations.rb
flexirest-1.3.4 lib/flexirest/associations.rb
flexirest-1.3.3 lib/flexirest/associations.rb
flexirest-1.3.2 lib/flexirest/associations.rb
flexirest-1.3.1 lib/flexirest/associations.rb