Module: NoBrainer::Document::VirtualAttributes::ClassMethods

Defined in:
lib/no_brainer/document/virtual_attributes.rb

Instance Method Summary collapse

Instance Method Details

#field(attr, options = {}) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/no_brainer/document/virtual_attributes.rb', line 19

def field(attr, options={})
  return super unless options.key?(:virtual)

  raise "virtual attributes are limited to the root class `#{self.root_class}' for the moment.\n" +
        "Ask on GitHub for polymorphic support." unless is_root_class?

  raise "You cannot index a virtual attribute. Use an index with a lambda expression instead" if options[:index]
  options.assert_valid_keys(*VALID_VIRTUAL_FIELD_OPTIONS)

  self.virtual_fields ||= Set.new
  virtual_fields << attr

  inject_in_layer :virtual_attributes do
    define_method("#{attr}=") do |value|
      raise NoBrainer::Error::ReadonlyField.new("#{attr} is a virtual attribute and thus readonly.")
    end
  end

  super
end

#remove_field(attr, options = {}) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
# File 'lib/no_brainer/document/virtual_attributes.rb', line 40

def remove_field(attr, options={})
  super

  if fields[:virtual]
    virtual_fields.try(:delete, attr)

    inject_in_layer :virtual_attributes do
      remove_method("#{attr}=")
    end
  end
end

#virtual_field(attr, rql = nil, options = {}, &block) ⇒ Object



12
13
14
15
16
17
# File 'lib/no_brainer/document/virtual_attributes.rb', line 12

def virtual_field(attr, rql=nil, options={}, &block)
  rql, options = nil, rql if rql.is_a?(Hash)
  rql ||= block
  rql_proc = rql.is_a?(Proc) ? rql : proc { rql }
  field(attr, options.merge(:virtual => rql_proc))
end