Module: NoBrainer::Document::Attributes::ClassMethods
- Defined in:
- lib/no_brainer/document/attributes.rb
Instance Method Summary collapse
- #ensure_valid_key!(keys) ⇒ Object
- #field(attr, options = {}) ⇒ Object
- #has_field?(attr) ⇒ Boolean
- #inherited(subclass) ⇒ Object
- #new_from_db(attrs, options = {}) ⇒ Object
- #remove_field(attr, options = {}) ⇒ Object
Instance Method Details
#ensure_valid_key!(keys) ⇒ Object
157 158 159 160 161 162 163 164 165 166 167 168 |
# 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 = {}) ⇒ Object
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 |
# File 'lib/no_brainer/document/attributes.rb', line 121 def field(attr, ={}) .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!() 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) ⇒ Boolean
153 154 155 |
# File 'lib/no_brainer/document/attributes.rb', line 153 def has_field?(attr) !!fields[attr.to_sym] end |
#inherited(subclass) ⇒ Object
116 117 118 119 |
# File 'lib/no_brainer/document/attributes.rb', line 116 def inherited(subclass) subclass.fields = self.fields.dup super end |
#new_from_db(attrs, options = {}) ⇒ Object
111 112 113 114 |
# File 'lib/no_brainer/document/attributes.rb', line 111 def new_from_db(attrs, ={}) = .reverse_merge(:pristine => true, :from_db => true) model_from_attrs(attrs).new(attrs, ) if attrs end |
#remove_field(attr, options = {}) ⇒ Object
142 143 144 145 146 147 148 149 150 151 |
# File 'lib/no_brainer/document/attributes.rb', line 142 def remove_field(attr, ={}) inject_in_layer :attributes do remove_method("#{attr}=") remove_method("#{attr}") end subclass_tree.each do |subclass| subclass.fields.delete(attr) end end |