Module: EmbeddedRecord::Record::ClassMethods

Defined in:
lib/embedded_record.rb

Instance Method Summary collapse

Instance Method Details

#allObject

Returns all records



175
176
177
# File 'lib/embedded_record.rb', line 175

def all
  @records ||= []
end

#attribute(name) ⇒ Object

Defines a Symbol attribute for a record



230
231
232
233
234
235
236
# File 'lib/embedded_record.rb', line 230

def attribute(name)
  attributes << name

  if !method_defined?(name) || name == :id
    attr_accessor name
  end
end

#attributesObject

Returns Array of record attributes



157
158
159
# File 'lib/embedded_record.rb', line 157

def attributes
  @attributes ||= []
end

#find(id) ⇒ Object

Returns record for a given id or nil



169
170
171
# File 'lib/embedded_record.rb', line 169

def find(id)
  all.find { |obj| obj.id == id }
end

#firstObject

Returns first record



181
182
183
# File 'lib/embedded_record.rb', line 181

def first
  all.first
end

#idsObject

Returns Array of records ids



163
164
165
# File 'lib/embedded_record.rb', line 163

def ids
  @keys ||= []
end

#lastObject

Returns last record



187
188
189
# File 'lib/embedded_record.rb', line 187

def last
  all.last
end

#null_recordObject

Returns null record, a record which id is nil

Example:

class Foo
  record nil, :name => "Empty"
end

Foo.null_record.name # => "Empty"


224
225
226
# File 'lib/embedded_record.rb', line 224

def null_record
  @null_record
end

#record(id, attrs = {}) ⇒ Object

Defines a record with an id and Hash of attributes.



193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
# File 'lib/embedded_record.rb', line 193

def record(id, attrs = {})
  record = new
  record.send "id=", id
  attrs.each do |k, v|
    unless attributes.include? k
      raise ArgumentError, "Atrribute '#{k}' not found"
    end

    record.send "#{k}=", v
  end

  if id == nil
    def record.nil?; true end

    @null_record = record
  else
    ids << id
    all << record
  end
end