module StrongPresenter::Associable

Methods for defining presenter associations

Protected Class Methods

descendant_of(object_class, klass) click to toggle source
# File lib/strong_presenter/associable.rb, line 104
def self.descendant_of(object_class, klass)
  object_class.ancestors.include? klass.constantize
rescue NameError
  false
end
get_collection_presenter(klass) click to toggle source
# File lib/strong_presenter/associable.rb, line 110
def self.get_collection_presenter(klass)
  "#{"#{klass}".pluralize}Presenter".constantize
rescue NameError
  StrongPresenter::CollectionPresenter
end
get_orm_association_info(object_class, association) click to toggle source
# File lib/strong_presenter/associable.rb, line 96
def self.get_orm_association_info(object_class, association)
  if descendant_of(object_class, "ActiveRecord::Reflection")
    object_class.reflect_on_association(association).instance_eval { [klass, collection?] }
  else
    nil
  end
end
object_association_class(object_class, association) click to toggle source

infer association class if possible

# File lib/strong_presenter/associable.rb, line 88
def self.object_association_class(object_class, association)
  klass, collection = get_orm_association_info(object_class, association)
  return nil if klass.nil?
  "#{klass}Presenter".constantize
rescue NameError
  get_collection_presenter(klass) if collection # else nil
end

Public Instance Methods

permit!(*attribute_paths) click to toggle source

Permits given attributes, with propagation to associations.

Calls superclass method
# File lib/strong_presenter/associable.rb, line 60
def permit! *attribute_paths
  super
  attribute_paths.each do |path| # propagate permit to associations
    path = Array(path)
    if path == [:**]
      presenter_associations.each_value { |presenter| presenter.permit! [:**]}
    elsif path.size>1
      association = path[0].to_sym
      presenter_associations[association].permit! path.drop(1) if presenter_associations.has_key?(association)
    end
  end
  self
end
reload!() click to toggle source

Resets association presenters - clears the cache

# File lib/strong_presenter/associable.rb, line 75
def reload!
  @presenter_associations.clear
  self
end

Private Instance Methods

presenter_associations() click to toggle source
# File lib/strong_presenter/associable.rb, line 81
def presenter_associations
  @presenter_associations ||= {}
end