Module: Bank::Collection

Extended by:
Forwardable
Defined in:
lib/bank/collection.rb

Instance Method Summary collapse

Instance Method Details

#configObject



21
22
23
# File 'lib/bank/collection.rb', line 21

def config
  @_config ||= CollectionConfig.new
end

#convert(attrs) ⇒ Object



75
76
77
78
79
80
81
82
83
84
# File 'lib/bank/collection.rb', line 75

def convert(attrs)
  case attrs
  when Array
    attrs.map(&method(:convert))
  when Hash
    config.model.new(Serialize.unpack(config, attrs))
  else
    raise UnknownConversionType, "unable to convert #{attrs.inspect}"
  end
end

#create(attrs) ⇒ Object



50
51
52
# File 'lib/bank/collection.rb', line 50

def create(attrs)
  save(config.model.new(attrs))
end

#dbObject



25
26
27
# File 'lib/bank/collection.rb', line 25

def db
  Result.new(config.db, self)
end

#delete(key) ⇒ Object



71
72
73
# File 'lib/bank/collection.rb', line 71

def delete(key)
  db.where(config.primary_key => key).delete
end

#find(key) ⇒ Object

Raises:



62
63
64
65
66
67
68
69
# File 'lib/bank/collection.rb', line 62

def find(key)
  result = key.nil? ? nil : where(config.primary_key => key).first

  raise RecordNotFound,
    "no record found in collection with id `#{key.inspect}'" if result.nil?

  return result
end

#find_by(key, value) ⇒ Object



33
34
35
# File 'lib/bank/collection.rb', line 33

def find_by(key, value)
  where(key => value).first
end

#initialize(&block) ⇒ Object



17
18
19
# File 'lib/bank/collection.rb', line 17

def initialize(&block)
  instance_exec &block
end

#join_select(table, *args, &blk) ⇒ Object



86
87
88
89
# File 'lib/bank/collection.rb', line 86

def join_select(table, *args, &blk)
  select(*config.model.config._fields.map { |f| :"#{table}__#{f}"}).
    join(*args, &blk)
end

#new?(model) ⇒ Boolean

Returns:

  • (Boolean)


91
92
93
# File 'lib/bank/collection.rb', line 91

def new?(model)
  model.send(config.primary_key).nil?
end

#save(model) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/bank/collection.rb', line 37

def save(model)
  pkey = config.primary_key

  if new?(model)
    model.send(:"#{pkey}=", db.insert(Serialize.pack(config, model)))
  else
    db.where(pkey => model.send(pkey)).
      update(Serialize.pack(config, model))
  end

  return model
end

#scope(name, blk) ⇒ Object



29
30
31
# File 'lib/bank/collection.rb', line 29

def scope(name, blk)
    define_singleton_method(name) { |*args| instance_exec *args, &blk }
end

#update(*args, &blk) ⇒ Object



54
55
56
57
58
59
60
# File 'lib/bank/collection.rb', line 54

def update(*args, &blk)
  model = find(*args)

  blk.call(model)
  save(model)
  model
end