Module: Partisan::Followable

Extended by:
ActiveModel::Callbacks, ActiveSupport::Concern
Defined in:
lib/partisan/followable.rb

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(m, *args) ⇒ Object



59
60
61
62
63
64
65
66
67
# File 'lib/partisan/followable.rb', line 59

def method_missing(m, *args)
  if m.to_s[/(.+)_follower_(.+)s$/]
    follower_fields_by_type($1.singularize.classify, $2)
  elsif m.to_s[/(.+)_followers$/]
    followers_by_type($1.singularize.classify)
  else
    super
  end
end

Instance Method Details

#followed_by?(resource) ⇒ Boolean

Return true or false if the resource is following another

Examples:


@team.followed_by?(@user)

Returns:

  • (Boolean)


20
21
22
# File 'lib/partisan/followable.rb', line 20

def followed_by?(resource)
  resource.following?(self)
end

#follower_fields_by_type(follower_type, follower_field) ⇒ Array

Get ids of resources following self Use #pluck for an optimized sql query

Examples:


@team.following_ids_by_type('User')

Returns:

  • (Array)


49
50
51
# File 'lib/partisan/followable.rb', line 49

def follower_fields_by_type(follower_type, follower_field)
  followers_by_type(follower_type).pluck("#{follower_type.tableize}.#{follower_field}")
end

#followers_by_type(follower_type) ⇒ ActiveRecord::Relation

Get resource records for a specific type, used by #method_missing It conveniently returns an ActiveRecord::Relation for easy chaining of useful ActiveRecord methods

Examples:


@team.followers_by_type('User')

Returns:

  • (ActiveRecord::Relation)


32
33
34
35
36
37
38
39
# File 'lib/partisan/followable.rb', line 32

def followers_by_type(follower_type)
  opts = {
    'follows.followable_id' => self.id,
    'follows.followable_type' => Partisan::Helper.parent_class_name(self)
  }

  follower_type.constantize.joins(:follows).where(opts)
end

#respond_to?(m, include_private = false) ⇒ Boolean

Returns:

  • (Boolean)


69
70
71
# File 'lib/partisan/followable.rb', line 69

def respond_to?(m, include_private = false)
  super || m.to_s[/(.+)_follower_(.+)s$/] || m.to_s[/(.+)_follower/]
end

#update_followers_counterObject

Update cache counter Called in after_create and after_destroy



55
56
57
# File 'lib/partisan/followable.rb', line 55

def update_followers_counter
  self.update_attribute('followers_count', self.followings.count) if self.respond_to?(:followers_count)
end