Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
SearchObserver after creating ObserverSearchData
class SearchObserver < ActiveRecord::Observer
observe :topic, :post, :user, :category
def self.update_index(table, id, search_data)
table_name = "#{table}_search_data"
foreign_key = "#{table}_id"
# Would be nice to use AR here but not sure how to execut Postgres functions
# when inserting data like this.
rows = Post.exec_sql_row_count("UPDATE #{table_name} SET search_data = TO_TSVECTOR('english', ?) WHERE #{foreign_key} = ?", search_data, id)
if rows == 0
Post.exec_sql("INSERT INTO #{table_name} (#{foreign_key}, search_data) VALUES (?, TO_TSVECTOR('english', ?))", id, search_data)
end
rescue
# don't allow concurrency to mess up saving a post
end
def self.update_posts_index(observer_search_data)
update_index('post', observer_search_data.id, observer_search_data.search_data)
end
def self.update_users_index(observer_search_data)
update_index('user', observer_search_data.id, observer_search_data.search_data)
end
def self.update_categories_index(observer_search_data)
update_index('category', observer_search_data.id, observer_search_data.search_data)
end
def after_save(obj)
if obj.class == Post && obj.cooked_changed?
search_data = obj.scrubbed_html << " " << obj.topic.title
search_data << " " << obj.topic.category.name if obj.topic.category
observer_search_data = ObserverSearchData.new(obj.id, search_data)
SearchObserver.update_posts_index(observer_search_data)
end
if obj.class == User && (obj.username_changed? || obj.name_changed?)
search_data = obj.username.dup << " " << (obj.name || "")
observer_search_data = ObserverSearchData.new(obj.id, search_data)
SearchObserver.update_users_index(observer_search_data)
end
if obj.class == Topic && obj.title_changed?
if obj.posts
post = obj.posts.where(post_number: 1).first
if post
search_data = post.scrubbed_html << " " << obj.title
search_data << " " << obj.category.name if obj.category
observer_search_data = ObserverSearchData.new(post.id, search_data)
SearchObserver.update_posts_index(observer_search_data)
end
end
end
if obj.class == Category && obj.name_changed?
observer_search_data = ObserverSearchData.new(obj.id, obj.name)
SearchObserver.update_categories_index(observer_search_data)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment