Module: FirestoreODM::Schema

Included in:
Model
Defined in:
lib/firestore-odm/schema.rb

Instance Method Summary collapse

Instance Method Details

#contains(*models) ⇒ Object

Parameters:

  • models (Database::Model)


45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# 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 = {}) ⇒ Object

Defines a field.

Parameters:

  • name (String, Symbol)

    the field’s name.

  • type (Class)

    the field’s type.

  • opts (Hash) (defaults to: {})

    the field’s options.



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# 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 = {}) ⇒ Object

Defines a reference field.

Parameters:

  • name (String, Symbol)

    the reference’s name.

  • model (Database::Model)

    the reference’s model.

  • opts (Hash) (defaults to: {})

    the reference’s options.



37
38
39
40
41
# 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