Sha256: d3d15616166ce1005d26475e0a2dd1d745c57d1c1e207a66d89c61f24c1ee023

Contents?: true

Size: 1.52 KB

Versions: 16

Compression:

Stored size: 1.52 KB

Contents

module JsonApiClient
  module Helpers
    module Associable
      extend ActiveSupport::Concern

      included do
        class_attribute :associations
        self.associations = []

        include Associations::BelongsTo
        include Associations::HasMany
        include Associations::HasOne

        initializer :load_associations
      end

      module ClassMethods
        def belongs_to_associations
          associations.select{|association| association.is_a?(Associations::BelongsTo::Association) }
        end

        def prefix_params
          belongs_to_associations.map(&:param)
        end

        def prefix_path
          belongs_to_associations.map(&:to_prefix_path).join("/")
        end

        def path(params = nil)
          parts = [table_name]
          if params
            slurp = params.slice(*prefix_params)
            prefix_params.each do |param|
              params.delete(param)
            end
            parts.unshift(prefix_path % slurp)
          else
            parts.unshift(prefix_path)
          end
          parts.reject!{|part| part == "" }
          File.join(*parts)
        rescue KeyError
          raise ArgumentError, "Not all prefix parameters specified"
        end
      end

      protected

      def load_associations(params)
        associations.each do |association|
          if params.has_key?(association.attr_name.to_s)
            set_attribute(association.attr_name, association.parse(params[association.attr_name.to_s]))
          end
        end
      end

    end
  end
end

Version data entries

16 entries across 16 versions & 1 rubygems

Version Path
json_api_client-0.7.1 lib/json_api_client/helpers/associable.rb
json_api_client-0.7.0 lib/json_api_client/helpers/associable.rb
json_api_client-0.6.0 lib/json_api_client/helpers/associable.rb
json_api_client-0.5.1 lib/json_api_client/helpers/associable.rb
json_api_client-0.5.0 lib/json_api_client/helpers/associable.rb
json_api_client-0.4.0 lib/json_api_client/helpers/associable.rb
json_api_client-0.3.1 lib/json_api_client/helpers/associable.rb
json_api_client-0.3.0 lib/json_api_client/helpers/associable.rb
json_api_client-0.2.4 lib/json_api_client/helpers/associable.rb
json_api_client-0.2.3 lib/json_api_client/helpers/associable.rb
json_api_client-0.2.2 lib/json_api_client/helpers/associable.rb
json_api_client-0.2.1 lib/json_api_client/helpers/associable.rb
json_api_client-0.2.0 lib/json_api_client/helpers/associable.rb
json_api_client-0.1.3 lib/json_api_client/helpers/associable.rb
json_api_client-0.1.2 lib/json_api_client/helpers/associable.rb
json_api_client-0.1.1 lib/json_api_client/helpers/associable.rb