Sha256: 543ff2818121adaa1e4cb2cf7e1fa3a9a63c697c2dbcfc41c1f5ede80022c652

Contents?: true

Size: 1.04 KB

Versions: 12

Compression:

Stored size: 1.04 KB

Contents

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

  module ClassMethods
    def find(id)
      row = db.select(table_name, {id: id}, limit: 1).fetch
      raise BazaModels::Errors::RecordNotFound, "Record not found by ID: #{id}" unless row
      new(row, init: true)
    end

    def find_by(where_hash)
      where(where_hash).first
    end

    def find_by!(where_hash)
      model = find_by(where_hash)
      return model if model
      raise BazaModels::Errors::RecordNotFound, "Record not found by arguments: #{where_hash}" unless model
    end

    def find_or_initialize_by(data)
      model = find_by(data)
      return model if model
      new(data)
    end

    def find_or_create_by(data)
      model = find_or_initialize_by(data)
      model.save if model.new_record?
      yield model if block_given?
      model
    end

    def find_or_create_by!(data)
      model = find_or_initialize_by(data)
      model.save! if model.new_record?
      yield model if block_given?
      model
    end
  end
end

Version data entries

12 entries across 12 versions & 1 rubygems

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