module FirestoreODM::Schema

Public Instance Methods

contains(*models) click to toggle source

@param models [Database::Model]

# File lib/firestore-odm/schema.rb, line 45
def contains *models
  models.each do |model|
    name = model.name.downcase
    
    define_method("create_#{name}") do |opts = {}, &block|
      opts = {:relative_to => document}.merge opts
      model.create(opts, &block)
    end
    
    define_method("create_#{name}_with_id") do |id, opts = {}, &block|
      opts = {:relative_to => document}.merge opts
      model.create_with_id(id, opts, &block)
    end
    
    define_method("#{name}_from_id") do |id, opts = {}|
      opts = {:relative_to => document}.merge opts
      model.from_id(id, opts)
    end
  end
end
field(name, type, opts = {}) click to toggle source

Defines a field. @param name [String, Symbol] the field's name. @param type [Class] the field's type. @param opts [Hash] the field's options.

# File lib/firestore-odm/schema.rb, line 7
def field name, type, opts = {}
  conversion = FirestoreODM.get_conversion type

  list = []
  
  list << FirestoreODM.get_option(:min, opts[:min]) if opts[:min]
  list << FirestoreODM.get_option(:max, opts[:max]) if opts[:max]
  list << FirestoreODM.get_option(:less_than, opts[:less_than]) if opts[:less_than]
  list << FirestoreODM.get_option(:more_than, opts[:more_than]) if opts[:more_than]
  list << FirestoreODM.get_option(:in, opts[:in]) if opts[:in]

  define_singleton_method("parse_#{name}") do |value|
    list.reduce(true) { |result, o| result and o.call(value) }
  end

  define_method(name) { self[name] }
  
  define_method("#{name}=") do |value|
    value = conversion.call value
    raise "#{value} is not a valid value for field #{name}" unless self.class.method("parse_#{name}").call value
    self[name] = value
  end

  return
end
reference(name, model, opts = {}) click to toggle source

Defines a reference field. @param name [String, Symbol] the reference's name. @param model [Database::Model] the reference's model. @param opts [Hash] the reference's options.

# File lib/firestore-odm/schema.rb, line 37
def reference name, model, opts = {}
  define_method(name) { model.new self[name] }
  define_method("#{name}=") { |value| self[name] = value.document }
  return
end