Sha256: 596df58ac462536ef6c779a483f2703c4f34e007f5eb662125d9703dda5204ad

Contents?: true

Size: 1.65 KB

Versions: 10

Compression:

Stored size: 1.65 KB

Contents

require 'spyke/associations/association'
require 'spyke/associations/has_many'
require 'spyke/associations/has_one'
require 'spyke/associations/belongs_to'

module Spyke
  module Associations
    extend ActiveSupport::Concern

    included do
      class_attribute :associations
      self.associations = {}.freeze
    end

    module ClassMethods
      def has_many(name, options = {})
        self.associations = associations.merge(name => options.merge(type: HasMany))

        define_method "#{name.to_s.singularize}_ids=" do |ids|
          attributes[name] = []
          ids.reject(&:blank?).each { |id| association(name).build(id: id) }
        end

        define_method "#{name.to_s.singularize}_ids" do
          association(name).map(&:id)
        end
      end

      def has_one(name, options = {})
        self.associations = associations.merge(name => options.merge(type: HasOne))
        define_method "build_#{name}" do |attributes = nil|
          association(name).build(attributes)
        end
      end

      def belongs_to(name, options = {})
        self.associations = associations.merge(name => options.merge(type: BelongsTo))
      end

      def accepts_nested_attributes_for(*names)
        names.each do |association_name|
          class_eval <<-RUBY, __FILE__, __LINE__ + 1
            def #{association_name}_attributes=(association_attributes)
              association(:#{association_name}).assign_nested_attributes(association_attributes)
            end
          RUBY
        end
      end

      def reflect_on_association(name)
        Relation.new(name.to_s.classify.constantize) # Just enough to support nested_form gem
      end
    end
  end
end

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
spyke-1.4.0 lib/spyke/associations.rb
spyke-1.3.0 lib/spyke/associations.rb
spyke-1.2.1 lib/spyke/associations.rb
spyke-1.2.0 lib/spyke/associations.rb
spyke-1.1.2 lib/spyke/associations.rb
spyke-1.1.1 lib/spyke/associations.rb
spyke-1.1.0 lib/spyke/associations.rb
spyke-1.0.2 lib/spyke/associations.rb
spyke-1.0.1 lib/spyke/associations.rb
spyke-1.0.0 lib/spyke/associations.rb