module NoBrainer::Document::Attributes::ClassMethods

Public Instance Methods

ensure_valid_key!(keys) click to toggle source
# File lib/no_brainer/document/attributes.rb, line 157
def ensure_valid_key!(keys)
  missings = Array(keys).select do |key|
    has_field?(key) == false && has_index?(key) == false
  end

  return if missings.empty?

  raise NoBrainer::Error::UnknownAttribute,
        "`#{missings.join('\', `')}' #{missings.size > 1 ? 'are' : 'is'} " \
        "not #{'a' if missings.size == 1} valid attribute" \
        "#{'s' if missings.size > 1} of #{self}"
end
field(attr, options={}) click to toggle source
# File lib/no_brainer/document/attributes.rb, line 121
def field(attr, options={})
  options.assert_valid_keys(*VALID_FIELD_OPTIONS)
  unless attr.is_a?(Symbol)
    raise "The field `#{attr}' must be declared with a Symbol" # we're just being lazy here...
  end
  if attr.in?(RESERVED_FIELD_NAMES)
    raise "The field name `:#{attr}' is reserved. Please use another one."
  end

  subclass_tree.each do |subclass|
    subclass.fields[attr] ||= {}
    subclass.fields[attr].deep_merge!(options)
  end

  attr = attr.to_s
  inject_in_layer :attributes do
    define_method("#{attr}=") { |value| _write_attribute(attr, value) }
    define_method("#{attr}") { _read_attribute(attr) }
  end
end
has_field?(attr) click to toggle source
# File lib/no_brainer/document/attributes.rb, line 153
def has_field?(attr)
  !!fields[attr.to_sym]
end
inherited(subclass) click to toggle source
Calls superclass method
# File lib/no_brainer/document/attributes.rb, line 116
def inherited(subclass)
  subclass.fields = self.fields.dup
  super
end
new_from_db(attrs, options={}) click to toggle source
# File lib/no_brainer/document/attributes.rb, line 111
def new_from_db(attrs, options={})
  options = options.reverse_merge(:pristine => true, :from_db => true)
  model_from_attrs(attrs).new(attrs, options) if attrs
end
remove_field(attr, options={}) click to toggle source
# File lib/no_brainer/document/attributes.rb, line 142
def remove_field(attr, options={})
  inject_in_layer :attributes do
    remove_method("#{attr}=")
    remove_method("#{attr}")
  end

  subclass_tree.each do |subclass|
    subclass.fields.delete(attr)
  end
end