Module: Sinja::Sequel::Helpers
- Defined in:
- lib/sinja/sequel/helpers.rb
Class Method Summary collapse
Instance Method Summary collapse
- #add_missing(*args, &block) ⇒ Object
- #add_remove(association, rios, try_convert = :to_i, **filters, &block) ⇒ Object
- #next_pk(resource, opts = {}) ⇒ Object
- #remove_present(*args, &block) ⇒ Object
Class Method Details
.included(base) ⇒ Object
7 8 9 |
# File 'lib/sinja/sequel/helpers.rb', line 7 def self.included(base) base.prepend(Core) end |
Instance Method Details
#add_missing(*args, &block) ⇒ Object
51 52 53 |
# File 'lib/sinja/sequel/helpers.rb', line 51 def add_missing(*args, &block) add_or_remove(:add, :-, *args, &block) end |
#add_remove(association, rios, try_convert = :to_i, **filters, &block) ⇒ Object
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
# File 'lib/sinja/sequel/helpers.rb', line 15 def add_remove(association, rios, try_convert=:to_i, **filters, &block) meth_suffix = association.to_s.singularize add_meth = "add_#{meth_suffix}".to_sym remove_meth = "remove_#{meth_suffix}".to_sym if block filters[:add] ||= block filters[:remove] ||= block end dataset = resource.send("#{association}_dataset") klass = dataset.association_reflection.associated_class # does not / will not work with composite primary keys new_ids = rios.map { |rio| proc(&try_convert).(rio[:id]) } transaction do resource.lock! old_ids = dataset.select_map(klass.primary_key) ids_in_common = old_ids & new_ids (new_ids - ids_in_common).each do |id| subresource = klass.with_pk!(id) next if filters[:add] && !filters[:add].(subresource) resource.send(add_meth, subresource) end (old_ids - ids_in_common).each do |id| subresource = klass.with_pk!(id) next if filters[:remove] && !filters[:remove].(subresource) resource.send(remove_meth, subresource) end resource.reload end end |
#next_pk(resource, opts = {}) ⇒ Object
11 12 13 |
# File 'lib/sinja/sequel/helpers.rb', line 11 def next_pk(resource, opts={}) [resource.pk, resource, opts] end |
#remove_present(*args, &block) ⇒ Object
55 56 57 |
# File 'lib/sinja/sequel/helpers.rb', line 55 def remove_present(*args, &block) add_or_remove(:remove, :&, *args, &block) end |