Sha256: dec2d77aa81026f8ac8e816309ea9a01734dec7a77b8fd12b3f2b5eb35318494

Contents?: true

Size: 1.35 KB

Versions: 5

Compression:

Stored size: 1.35 KB

Contents

module IAmICan
  module Association_ClassMethods
    def has_many_temporary_roles(name: nil)
      define_method :temporary_roles do
        @temporary_roles ||= [ ]
      end
      #
      alias_method name, :temporary_roles if name

      define_method :valid_temporary_roles do
        i_am_i_can.role_model.where(id: temporary_roles.map(&:id))
      end

      raise "Do not set the role association name to `roles` in #{self.class.name} model" if respond_to?(:roles)
      define_method :roles do
        ids = (temporary_roles.map(&:id) + _roles.ids).uniq
        i_am_i_can.role_model.where(id: ids)
      end

      define_method :temporary_role_names do
        temporary_roles.map(&:name).map(&:to_sym)
      end
      #
      alias_method "#{name.to_s.singularize}_names", :temporary_role_names if name

      define_method :_temporary_roles_add do |names|
        names -= temporary_role_names
        temporary_roles.concat(roles = i_am_i_can.role_model.where(name: names))
        roles.names
      end

      define_method :_temporary_roles_rmv do |names|
        (names & temporary_role_names).each do |n|
          temporary_roles.reject! { |i| i.name.to_sym == n }
        end
      end

      define_method :_temporary_roles_exec do |action = :assign, names|
        send('_temporary_roles_' + (action == :assign ? 'add' : 'rmv'), names)
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
i_am_i_can-4.3.2 lib/i_am_i_can/support/association_class_methods.rb
i_am_i_can-4.3.1 lib/i_am_i_can/support/association_class_methods.rb
i_am_i_can-4.3.0 lib/i_am_i_can/support/association_class_methods.rb
i_am_i_can-4.2.0 lib/i_am_i_can/support/association_class_methods.rb
i_am_i_can-4.1.0 lib/i_am_i_can/support/association_class_methods.rb