Skip to content

Instantly share code, notes, and snippets.

@michelson
Created July 15, 2016 04:58
Show Gist options
  • Save michelson/d9f18f87440fafac6fbcdf8547fd5217 to your computer and use it in GitHub Desktop.
Save michelson/d9f18f87440fafac6fbcdf8547fd5217 to your computer and use it in GitHub Desktop.
kind behavior
module Concerns
module KindBehavior
extend ActiveSupport::Concern
included do |base|
#base.extend( Concerns::KindBehavior::ModelClassMethods )
# usage
# => has_kinds [{relation: :event_kinds, source: "kind_event"}]
end
class_methods do
def kind_options
@kinds_options
end
def has_kinds(opts=[])
has_many :kind_taggings,
as: :taggable,
class_name: "Kind::Tagging",
autosave: true,
dependent: :destroy
@kind_options = opts
opts.each do |opt|
has_many :kinds,
through: :kind_taggings,
source: :tag,
source_type: "Kind::Base"
# TODO: encontrar una forma de fitrar por los taggfed with
has_many opt[:relation],
through: :kind_taggings,
source: :tag,
source_type: "Kind::Base"
accepts_nested_attributes_for opt[:relation], allow_destroy: true
generate_writter_for(opt)
define_method(:taggings_ids) do
self.kind_taggings.map{|o| o.tag_id}
end
end
end
def generate_writter_for(opt)
#will create event_kind_ids
define_method("#{opt[:relation].to_s.singularize}_ids=") do |ids|
existing_kinds_ids = self.send(opt[:relation]).tagged_with(opt[:source]).map(&:id)
to_remove = existing_kinds_ids - ids.map(&:to_i)
#self.send(opt[:relation]).map(&:id) - ids.map(&:to_i)
#if to_remove.any?
# self.kind_taggings.where(tag_id: to_remove)
# .each{|o| o.mark_for_destruction }
#end
self.kind_taggings.each{|o| o.mark_for_destruction if to_remove.include?(o.tag_id)}
ids.each do |i|
next if i.blank?
next if existing_kinds_ids.include?(i.to_i)
k = Kind::Base
.tagged_with(opt[:source], on: "kind_groups")
.find(i)
self.kind_taggings.new(tag: k, taggable: self) unless k.blank? #|| self.send(opt[:relation]).include?(k)
end
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment