Commit 6c54d1c330e4c40e70a393524d1dce5e74b6047a
1 parent
bacb490a
Exists in
master
and in
29 other branches
Filter profile by location
Showing
1 changed file
with
42 additions
and
0 deletions
Show diff stats
app/models/profile.rb
@@ -100,6 +100,48 @@ class Profile < ActiveRecord::Base | @@ -100,6 +100,48 @@ class Profile < ActiveRecord::Base | ||
100 | } | 100 | } |
101 | scope :no_templates, {:conditions => {:is_template => false}} | 101 | scope :no_templates, {:conditions => {:is_template => false}} |
102 | 102 | ||
103 | + # Returns a scoped object to select profiles in a given location or in a radius | ||
104 | + # distance from the given location center. | ||
105 | + # The parameter can be the `request.params` with the keys: | ||
106 | + # * `country`: Country code string. | ||
107 | + # * `state`: Second-level administrative country subdivisions. | ||
108 | + # * `city`: City full name for center definition, or as set by users. | ||
109 | + # * `lat`: The latitude to define the center of georef search. | ||
110 | + # * `lng`: The longitude to define the center of georef search. | ||
111 | + # * `distance`: Define the search radius in kilometers. | ||
112 | + # NOTE: This method may return an exception object, to inform filter error. | ||
113 | + # When chaining scopes, is hardly recommended you to add this as the last one, | ||
114 | + # if you can't be sure about the provided parameters. | ||
115 | + def self.by_location(params) | ||
116 | + params = params.with_indifferent_access | ||
117 | + if params[:distance].blank? | ||
118 | + where_code = [] | ||
119 | + [ :city, :state, :country ].each do |place| | ||
120 | + unless params[place].blank? | ||
121 | + # ... So we must to find on this named location | ||
122 | + # TODO: convert location attrs to a table collumn | ||
123 | + where_code << "(profiles.data like '%#{place}: #{params[place]}%')" | ||
124 | + end | ||
125 | + end | ||
126 | + self.where where_code.join(' AND ') | ||
127 | + else # Filter in a georef circle | ||
128 | + unless params[:lat].blank? && params[:lng].blank? | ||
129 | + lat, lng = [ params[:lat].to_f, params[:lng].to_f ] | ||
130 | + end | ||
131 | + if !lat | ||
132 | + location = [ params[:city], params[:state], params[:country] ].compact.join(', ') | ||
133 | + if location.blank? | ||
134 | + return Exception.new ( | ||
135 | + _('You must to provide `lat` and `lng`, or `city` and `country` to define the center of the search circle, defined by `distance`.') | ||
136 | + ) | ||
137 | + end | ||
138 | + lat, lng = Noosfero::GeoRef.location_to_georef location | ||
139 | + end | ||
140 | + dist = params[:distance].to_f | ||
141 | + self.where "#{Noosfero::GeoRef.sql_dist lat, lng} <= #{dist}" | ||
142 | + end | ||
143 | + end | ||
144 | + | ||
103 | include TimeScopes | 145 | include TimeScopes |
104 | 146 | ||
105 | def members | 147 | def members |