Module: HashDB::Model::ClassMethods
- Defined in:
- lib/hash_db/model/core.rb,
lib/hash_db/model/query.rb,
lib/hash_db/model/association.rb
Instance Attribute Summary collapse
-
#all ⇒ Object
Returns the value of attribute all.
Instance Method Summary collapse
- #belongs_to(name, args = {}) ⇒ Object
- #create(args = {}) ⇒ Object
- #find_by(*args) ⇒ Object
- #has_many(name, args = {}) ⇒ Object
- #keys(*keys) ⇒ Object
- #where(*args) ⇒ Object
Instance Attribute Details
#all ⇒ Object
Returns the value of attribute all.
38 39 40 |
# File 'lib/hash_db/model/core.rb', line 38 def all @all end |
Instance Method Details
#belongs_to(name, args = {}) ⇒ Object
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
# File 'lib/hash_db/model/association.rb', line 29 def belongs_to(name, args = {}) klass = args[:class] key = args[:key] define_method "#{name}" do @attributes[name] end define_method "#{name}=" do |object| @attributes[name] = object end define_method "#{key}" do @attributes[name] && @attributes[name].id end define_method "#{key}=" do |id| @attributes[name] = klass.find_by(id: id) end end |
#create(args = {}) ⇒ Object
52 53 54 55 56 |
# File 'lib/hash_db/model/core.rb', line 52 def create(args = {}) new(args).tap do |object| object.save end end |
#find_by(*args) ⇒ Object
23 24 25 26 |
# File 'lib/hash_db/model/query.rb', line 23 def find_by(*args) # Not efficient, and I know it. where(*args).first end |
#has_many(name, args = {}) ⇒ Object
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
# File 'lib/hash_db/model/association.rb', line 4 def has_many(name, args = {}) klass = args[:class] foreign_key = args[:foreign_key] klass.keys foreign_key define_method "#{name}" do base_id = id @attributes[name] ||= begin [].tap do |array| array.define_singleton_method :<< do |object| object.send("#{foreign_key}=", base_id) super object end array.define_singleton_method :create do |*args| klass.create(*args).tap do |object| array << object end end end end end end |
#keys(*keys) ⇒ Object
40 41 42 43 44 45 46 47 48 49 50 |
# File 'lib/hash_db/model/core.rb', line 40 def keys(*keys) keys.each do |key| define_method "#{key}" do @attributes[key] end define_method "#{key}=" do |value| @attributes[key] = value end end end |
#where(*args) ⇒ Object
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
# File 'lib/hash_db/model/query.rb', line 4 def where(*args) # Doesn't really take all cases into account. # Good enough for now. :) if args.size == 1 && Hash === args.first args = args.first.map do |key, value| [key, :==, value] end elsif !(Array === args.first) args = [args] end @all.values.select do |object| args.all? do |key, method, value| # TODO: Should access through the getter? object.attributes[key].send(method, value) end end end |