Checking to see if I'm following single responsibility principle

Alex1100
2017-06-16T23:39:11Z

location.rb

| class Location < ApplicationRecord
| require 'json'
|
| require 'uri'
|
| require 'net/http'
|
| belongs_to :user
|
| has_many :comments, as: :commentable, dependent: :destroy
|
| validates :address,
| presence: true
|
| def self.search(query)
| wildcarded_query = "%#{query}%"
| where(
| "address ILIKE :address OR name ILIKE :name",
| address: wildcarded_query,
| name: wildcarded_query
| )
| end
|
| def self.shelters_search(current_city, current_user_id)
| uri = URI.parse("https://maps.googleapis.com/maps/api/place/textsearch/json?query=homeless%20services+in+#{current_city.delete(' ')}&key=#{ENV["GOOGLE_PLACES_API_KEY"]}")
| response = Net::HTTP.get_response(uri)
| shelters = JSON.parse(response.body)["results"]
| if current_user_id
| location_attrs = []
|
| shelters.each_with_index do |shelter|
| location_attrs << {address: shelter['formatted_address'], latitude: shelter['geometry']['location']['lat'], longitude: shelter['geometry']['location']['lng'], name: shelter['name'], rating: shelter['rating'], user_id: current_user_id}
| end
|
| Location.bulk_insert values: location_attrs
| end
| end
|
| def self.walking_distance(current_city, address, user_location)
| uri = URI.parse("https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&avoid=tolls|highways|ferries|indoor&origins=#{current_city}&destinations=#{address.delete(' ')}&mode=walking&key=#{ENV["GOOGLE_MAPS_DISTANCE_MATRIX_API_KEY"]}")
| response = Net::HTTP.get_response(uri)
| distance = JSON.parse(response.body)["rows"]
| distance = distance[0]
| eta = JSON.parse(response.body)["rows"]
| eta = eta[0]
| if user_location && distance != {"elements"=>[{"status"=>"NOT_FOUND"}]} && eta != {"elements"=>[{"status"=>"NOT_FOUND"}]}
| "#{address} is #{distance["elements"][0]["distance"]["text"]} away from #{current_city} and it would take #{eta["elements"][0]["duration"]["text"]} via walking."
| else
| "N/A"
| end
| end
|
| def self.bicycling_distance(current_city, address, user_location)
| uri = URI.parse("https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&avoid=tolls|highways|ferries|indoor&origins=#{current_city}&destinations=#{address.delete(' ')}&mode=bicycling&key=#{ENV["GOOGLE_MAPS_DISTANCE_MATRIX_API_KEY"]}")
| response = Net::HTTP.get_response(uri)
| distance = JSON.parse(response.body)["rows"]
| distance = distance[0]
| eta = JSON.parse(response.body)["rows"]
| eta = eta[0]
| puts "\nTHE DISTANCE OBJECT IS: #{distance}"
| puts "\nTHE ETA OBJECT IS: #{eta}\n"
| if user_location && distance != {"elements"=>[{"status"=>"NOT_FOUND"}]} && eta != {"elements"=>[{"status"=>"NOT_FOUND"}]}
| "#{address} is #{distance["elements"][0]["distance"]["text"]} away from #{current_city} and it would take #{eta["elements"][0]["duration"]["text"]} via bicycling."
| else
| "N/A"
| end
| end
|
| end

locations_controller.rb

| class LocationsController < ApplicationController
| before_action :authorize, only: [:index, :generate_shelters, :logout]
| before_action :correct_user, only: [:generate_shelters, :logout]
|
| def index
| if params[:search]
| @searched_locations = search.page(params[:page]).per(10) if search
| end
| @local_locations = user_location_service.suggested_locations.page(params[:page]).per(10)
| @gmaps_coordinates = user_location_service.gmaps_coordinates
| end
|
| def generate_shelters
| @search_locations = Location.shelters_search(user.current_city, user.id)
| redirect_to root_path
| end
|
| def show
| @location = Location.find(params[:id])
| if current_user
| @suggested_locations = user_location_service.suggested_locations.page(params[:page]).per(10)
| @gmaps_coordinates = user_location_service.gmaps_coordinates
| @walking_distance = Location.walking_distance(user.current_city, @location.address, @location)
| @bicycling_distance = Location.bicycling_distance(user.current_city, @location.address, @location)
| elsif !current_user && @location.latitude && @location.longitude
| @gmaps_coordinates = [@location.latitude, @location.longitude]
| end
| end
|
| private
|
| def location_params
| params.require(:location).permit(:address, :latitude, :longitude, :user_id, :gmaps)
| end
|
| def user
| current_user
| end
|
| def correct_user
| @user = current_user
| redirect_to(root_path) unless current_user?(@user)
| end
|
| def user_params
| params.require(:user).permit(:current_city)
| end
|
| def user_location_service
| UserLocationService.new(current_user, search_term)
| end
|
| def search_term
| params[:search] if params[:search].present?
| end
|
| def local_search
| user_location_service.search_rslt
| end
|
| def search
| user_location_service.search_result
| end
|
| end

user.rb

| class User < ApplicationRecord
| has_secure_password
|
| has_many :locations
|
| has_many :comments, as: :commentable, dependent: :destroy
|
| validates :name, presence: true
|
| validates :username,
| presence: true,
| uniqueness: true
|
| validates :email,
| presence: true,
| uniqueness: { case_sensitive: false },
| format:
| {
| with: /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i,
| on: :create
| }
|
| validates :password,
| presence: true,
| length: 6..20,
| confirmation: true
|
| validates :current_city,
| presence: true
|
| validates :current_state,
| format:
| {
| with: %r{\A(?:(A[KLRZ]|B[C]|C[AOT]|D[CE]|FL|GA|HI|I[ADLN]|K[SY]|LA|M[ADEHINOST]|N[CDEHJMVY]|O[HKR]|P[AR]|RI|S[CD]|T[NX]|UT|V[AIT]|W[AIVY]))\z}, message: 'must be formatted as state initials. e.g. CA for California',
| :on => :create
| }
|
| validates :current_country,
| presence: true,
| format:
| {
| with: %r{\A(?-i:A[DEFGILMNOQRSTUWZ]|B[ABDEFGHIJMNORSTVWYZ]|C[ACDFGHIKLMNORSUVXYZ]|D[EJKMOZ]|E[CEGHRST]|F[IJKMOR]|G[ABDEFHILMNPQRSTUWY]|H[KMNRTU]|I[DELNOQRST]|J[MOP]|K[EGHIMNPRWYZ]|L[ABCIKRSTUVY]|M[ACDGHKLMNOPQRSTUVWXYZ]|N[ACEFGILOPRUZ]|O[M]|P[AEFGHKLMNRSTWY]|QA|R[EOUW]|S[ABCDEGHIJKLMNORTVYZ]|T[CDFGHJKLMNORTVWZ]|U[AGMSYZ]|V[ACEGINU]|W[FS]|Y[ET]|Z[AMW])\z}, message: 'must be formatted as US for United States',
| :on => :create
| }
|
| validates :bio,
| presence: true
|
| end

user_location_service.rb

| class UserLocationService
| attr_reader :current_user, :search_term
|
| def initialize(current_user, search_term = nil)
| @current_user = current_user
| @search_term = search_term
| end
|
| def user_city
| if current_user && current_user.locations.size > 0
| current_user.current_city
| elsif current_user && current_user.locations.size == 0
| "Los Angeles"
| end
| end
|
| def locations
| Location.all.order("name").group_by(&:address).values
| end
|
| def user_places
| locations.map{|a| a[0].address unless !a[0].address.include?(user_city)}
| end
|
| def user_locations
| Location.where(address: user_places)
| end
|
| def near_locations
| user_locations.order("name").group_by(&:address).values
| end
|
| def place_ids
| near_locations.map{|b| b[0].id}
| end
|
| def places_list
| Location.where(id: place_ids)
| end
|
| def suggested_locations
| places_list.order("name")
| end
|
| def gmaps_coordinates
| q = []
| if current_user && current_user.locations.size > 0
| q << places_list.last.try(:latitude)
| q << places_list.last.try(:longitude)
| elsif current_user && current_user.locations.size == 0
| q << places_list.last.try(:latitude)
| q << places_list.last.try(:longitude)
| else
| [34.0522, -118.2437]
| end
| end
|
| def all_places
| Location.all.search(search_term).order("name").group_by(&:address).values
| end
|
| def places
| Location.search(search_term).order("name").group_by(&:address).values
| end
|
| def identification
| all_places.map{|l| l[0].id} if all_places
| end
|
| def identify
| places.map{|l| l[0].id} if places
| end
|
| def search_result
| Location.where(id: identification) if identification
| end
|
| def search_rslt
| Location.where(id: identify) if identify
| end
|
| end

users_controller.rb

| class UsersController < ApplicationController
| before_action :authorize, only: [:edit, :update, :logout]
| before_action :correct_user, only: [:edit, :update, :logout]
|
| def index
| if current_user && current_user.locations.size > 0
| @suggested_locations = user_location_service.suggested_locations.page(params[:page]).per(10)
| @gmaps_coordinates = user_location_service.gmaps_coordinates
| if params[:search]
| @searched_places = search.page(params[:page]).per(10) if search
| end
| elsif current_user && current_user.locations.size == 0
| @suggested_locations = user_location_service.suggested_locations.page(params[:page]).per(10)
| @gmaps_coordinates = user_location_service.gmaps_coordinates
| if params[:search]
| @searched_places = search.page(params[:page]).per(10) if search
| end
| else
| @searched_places = search.page(params[:page]).per(10) if search
| end
| end
|
| def show
| @user = User.find(params[:id])
| @user_city = @user.current_city
| @locations = Location.all.order("name").group_by(&:address).values
| @user_places = @locations.map{|a| a[0].address unless !a[0].address.include?(@user_city)}
| @user_locations = Location.where(address: @user_places)
| @near_locations = @user_locations.order("name").group_by(&:address).values
| @ids = @near_locations.map{|b| b[0].id}
| @places_list = Location.where(id: @ids).order("name")
| @suggested_locations = @places_list.page(params[:page]).per(10)
| @gmaps_coordinates = [@places_list.last.try(:latitude), @places_list.last.try(:longitude)]
| end
|
| def edit
| @user = User.find(params[:id])
| @gmaps_coordinates = user_location_service.gmaps_coordinates
| end
|
| def new
| @user = User.new
| end
|
| def create
| @user = User.new(user_params)
| if @user.save
| session[:user_id] = @user.id
| flash[:notice] = "You have successfully signed up"
| redirect_to nearby_shelters_path(current_user.current_city, current_user.id)
| else
| render 'new'
| end
| end
|
| def update
| if @user.update(user_params)
| redirect_to user_path
| flash[:notice] = "Updated Profile"
| else
| redirect_to edit_user_path
| end
| end
|
| private
|
| def user_params
| params.require(:user).permit(:name, :username, :email, :current_city, :current_state, :current_country, :password, :password_confirmation, :bio)
| end
|
| def location_params
| params.require(:location).permit(:address, :latitude, :longitude, :user_id, :gmaps)
| end
|
| def correct_user
| @user = User.find(params[:id])
| redirect_to(root_path) unless current_user?(@user)
| end
|
| def user_location_service
| UserLocationService.new(current_user, search_term)
| end
|
| def search_term
| params[:search] if params[:search].present?
| end
|
| def search
| user_location_service.search_result
| end
|
| end