Skip to content

Instantly share code, notes, and snippets.

@lcguida
Created March 23, 2016 18:02
Show Gist options
  • Save lcguida/9d5eb533ae48ed2d65ba to your computer and use it in GitHub Desktop.
Save lcguida/9d5eb533ae48ed2d65ba to your computer and use it in GitHub Desktop.
Network Explorer (Tree view with different models)
class NetworkExplorerController < ApplicationController
def index
end
def get_root_nodes
roots = NetworkExplorerService.roots(current_user)
respond_with(roots)
end
def get_children_nodes
type, id = params[:type], params[:id]
nodes = NetworkExplorerService.children(type, id)
respond_with(nodes)
end
end
class NetworkExplorerService
class << self
def roots(user)
if user.admin?
root_regions = Region.without_parent #all root regions
else
root_regions = user.regions #Get only user permitted regions
end
root_regions.map { |region| region.as_tree_node.json_tree }
end
def children(type, id)
model = type.classify.constantize.find(id)
model.as_tree_node.children_json_tree
end
end
end
class Region < ActiveRecord::Base
has_many :sites
acts_as_nested_set # awesome nested set gem
#....
def as_tree_node
NetworkExplorer::RegionTreeNode.new(self)
end
end
module NetworkExplorer
class RegionTreeNode
def initialize(region)
@region = region
end
def json_tree
{
id: "region_#{@region.id}",
object_id: @region.id,
text: @region.name,
type: "region",
icon: "fa fa-globe",
children: has_children?
}
end
def has_children?
@region.children.any? || @region.sites.any? || @region.routes.any?
end
def children_json_tree
all_children = []
# Region
@region.children.each do |region|
all_children << region.as_tree_node.json_tree
end
# Sites
@region.sites.each do |site|
all_children << site.as_tree_node.json_tree
end
all_children
end
end
end
class Site < ActiveRecord::Base
has_many :rtus
has_many :distributors
#....
def as_tree_node
NetworkExplorer::SiteTreeNode.new(self)
end
end
module NetworkExplorer
class SiteTreeNode
def initialize(site)
@site = site
end
def json_tree
{
id: "site_#{@site.id}",
object_id: @site.id,
text: "#{@site.name} (#{@site.acronym})",
type: "site",
icon: "fa fa-building-o",
children: has_children?
}
end
def has_children?
@site.rtus.any? || @site.distributors.any?
end
def children_json_tree
all_children = []
# Rtus
@site.rtus.each do |rtu|
all_children << rtu.as_tree_node.json_tree
end
# Distributors
@site.distributors.each do |distributor|
all_children << distributor.as_tree_node.json_tree
end
all_children
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment