Class: Masterman::Relation
- Inherits:
-
Object
- Object
- Masterman::Relation
- Extended by:
- Forwardable
- Includes:
- Enumerable
- Defined in:
- lib/masterman/relation.rb
Instance Method Summary collapse
- #all ⇒ Object
- #find(id) ⇒ Object
- #find_by(attributes) ⇒ Object
- #ids ⇒ Object
-
#initialize(klass, records = []) ⇒ Relation
constructor
A new instance of Relation.
- #many? ⇒ Boolean
- #pluck(*column_names) ⇒ Object
- #to_a ⇒ Object
Constructor Details
#initialize(klass, records = []) ⇒ Relation
Returns a new instance of Relation.
13 14 15 16 |
# File 'lib/masterman/relation.rb', line 13 def initialize(klass, records = []) @klass = klass @instances = to_instances(records) end |
Instance Method Details
#all ⇒ Object
48 49 50 |
# File 'lib/masterman/relation.rb', line 48 def all to_a end |
#find(id) ⇒ Object
18 19 20 |
# File 'lib/masterman/relation.rb', line 18 def find(id) @instances[id] || raise(RecordNotFound.new('missing record')) end |
#find_by(attributes) ⇒ Object
22 23 24 25 26 27 28 |
# File 'lib/masterman/relation.rb', line 22 def find_by(attributes) @instances.each do |_, record| return record if attributes.all? { |key, value| record[key] == value } end nil end |
#ids ⇒ Object
40 41 42 |
# File 'lib/masterman/relation.rb', line 40 def ids pluck(@klass.masterman.primary_key) end |
#many? ⇒ Boolean
44 45 46 |
# File 'lib/masterman/relation.rb', line 44 def many? count > 1 end |
#pluck(*column_names) ⇒ Object
30 31 32 33 34 35 36 37 38 |
# File 'lib/masterman/relation.rb', line 30 def pluck(*column_names) if column_names.one? all.map { |record| record[column_names.first] } else all.map do |record| column_names.map { |name| record[name] } end end end |
#to_a ⇒ Object
52 53 54 |
# File 'lib/masterman/relation.rb', line 52 def to_a @instances.values end |