1
# The set_overrides extension adds the Dataset#set_overrides and
2
# Dataset#set_defaults methods which provide a crude way to
3
# control the values used in INSERT/UPDATE statements if a hash
4
# of values is passed to Dataset#insert or Dataset#update.
5
# It is only recommended to use this for backwards compatibility.
7
# You can load this extension into specific datasets:
10
# ds.extension(:set_overrides)
12
# Or you can load it into all of a database's datasets, which
13
# is probably the desired behavior if you are using this extension:
15
# DB.extension(:set_overrides)
19
Dataset::NON_SQL_OPTIONS.concat([:defaults, :overrides])
20
Dataset.def_mutation_method(:set_defaults, :set_overrides, :module=>self)
22
# Set overrides/defaults for insert hashes
23
def insert_sql(*values)
24
if values.size == 1 && (vals = values.first).is_a?(Hash)
25
super(merge_defaults_overrides(vals))
31
# Set the default values for insert and update statements. The values hash passed
32
# to insert or update are merged into this hash, so any values in the hash passed
33
# to insert or update will override values passed to this method.
35
# DB[:items].set_defaults(:a=>'a', :c=>'c').insert(:a=>'d', :b=>'b')
36
# # INSERT INTO items (a, c, b) VALUES ('d', 'c', 'b')
37
def set_defaults(hash)
38
clone(:defaults=>(@opts[:defaults]||{}).merge(hash))
41
# Set values that override hash arguments given to insert and update statements.
42
# This hash is merged into the hash provided to insert or update, so values
43
# will override any values given in the insert/update hashes.
45
# DB[:items].set_overrides(:a=>'a', :c=>'c').insert(:a=>'d', :b=>'b')
46
# # INSERT INTO items (a, c, b) VALUES ('a', 'c', 'b')
47
def set_overrides(hash)
48
clone(:overrides=>hash.merge(@opts[:overrides]||{}))
51
# Set overrides/defaults for update hashes
52
def update_sql(values = {})
54
super(merge_defaults_overrides(values))
62
# Return new hashe with merged defaults and overrides.
63
def merge_defaults_overrides(vals)
64
vals = @opts[:defaults].merge(vals) if @opts[:defaults]
65
vals = vals.merge(@opts[:overrides]) if @opts[:overrides]
70
Dataset.register_extension(:set_overrides, SetOverrides)