Sha256: e4e224442c388c78bc53f7f52b80bdb6cf1ffec5825686d4745b8d669093c5e9

Contents?: true

Size: 1.4 KB

Versions: 11

Compression:

Stored size: 1.4 KB

Contents

module BazaModels::Model::BelongsToRelations
  def self.included(base)
    base.extend(ClassMethods)
  end

  module ClassMethods
    def belongs_to(relation_name, args = {})
      relation = {
        type: :belongs_to,
        relation_name: relation_name,
        table_name: args[:table_name] || StringCases.pluralize(relation_name),
        foreign_key: :"#{relation_name}_id"
      }

      if args[:class_name]
        relation[:class_name] = args.fetch(:class_name)
      else
        relation[:class_name] = StringCases.snake_to_camel(relation_name)
      end

      @belongs_to_relations ||= []
      @belongs_to_relations << relation

      @relationships ||= {}
      @relationships[relation_name] = relation

      define_method(relation_name) do
        if (model = @changes[relation_name])
          model
        elsif (model = autoloads[relation_name])
          model
        else
          if relation[:class_name]
            class_name = relation.fetch(:class_name)
          else
            class_name = StringCases.snake_to_camel(relation_name)
          end

          foreign_id = @data.fetch(relation.fetch(:foreign_key))
          StringCases.constantize(class_name).find(foreign_id) if foreign_id
        end
      end

      define_method("#{relation_name}=") do |new_model|
        @changes[relation.fetch(:foreign_key)] = new_model.id
        autoloads.delete(relation_name)
      end
    end
  end
end

Version data entries

11 entries across 11 versions & 1 rubygems

Version Path
baza_models-0.0.13 lib/baza_models/model/belongs_to_relations.rb
baza_models-0.0.12 lib/baza_models/model/belongs_to_relations.rb
baza_models-0.0.11 lib/baza_models/model/belongs_to_relations.rb
baza_models-0.0.10 lib/baza_models/model/belongs_to_relations.rb
baza_models-0.0.9 lib/baza_models/model/belongs_to_relations.rb
baza_models-0.0.8 lib/baza_models/model/belongs_to_relations.rb
baza_models-0.0.7 lib/baza_models/model/belongs_to_relations.rb
baza_models-0.0.6 lib/baza_models/model/belongs_to_relations.rb
baza_models-0.0.5 lib/baza_models/model/belongs_to_relations.rb
baza_models-0.0.4 lib/baza_models/model/belongs_to_relations.rb
baza_models-0.0.3 lib/baza_models/model/belongs_to_relations.rb