lib/helpers/uwaterlooapi_query.rb in uwaterlooapi-0.0.2 vs lib/helpers/uwaterlooapi_query.rb in uwaterlooapi-0.0.3

- old
+ new

@@ -1,59 +1,40 @@ require 'recursive-open-struct' class UWaterlooAPIQuery include Routes - + def initialize(cur_route, cur_url, api_key) @api_key = api_key @cur_url = cur_url @cur_route = cur_route @retrieved_url = '' @response = @meta = nil - # Select only routes that may come next - routes = @@routes.select { |s| s.start_with?(cur_route) }. - map { |s| s[@cur_route.length..-1] }. - join.split('/').uniq.delete_if(&:empty?) - # Define methods without parameters - routes.reject { |r| r =~ /^\{.*\}$/ }. - map(&:to_sym).each do |route| - + get_next_routes_without_params.each do |route| self.class.send :define_method, route do - if is_in_routes?("#{@cur_route}/#{route}") - UWaterlooAPIQuery.new "#{@cur_route}/#{route}", "#{@cur_url}/#{route}", api_key - else - raise NoMethodError - end + raise NoMethodError unless is_in_routes?("#{@cur_route}/#{route}") + UWaterlooAPIQuery.new "#{@cur_route}/#{route}", "#{@cur_url}/#{route}", @api_key end end # Define methods with parameters - routes.select { |r| r =~ /^\{.*\}$/ }. - map { |r| r.delete('{}') }. - map(&:to_sym).each do |route| - + get_next_routes_with_params.each do |route| self.class.send :define_method, route do |value| raise ArgumentError if ["", 0].include? value - if is_in_routes?("#{@cur_route}/{#{route}}") - UWaterlooAPIQuery.new "#{@cur_route}/{#{route}}", "#{@cur_url}/#{value}", api_key - else - raise NoMethodError - end + raise NoMethodError unless is_in_routes?("#{@cur_route}/{#{route}}") + UWaterlooAPIQuery.new "#{@cur_route}/{#{route}}", "#{@cur_url}/#{value}", @api_key end end end # Get meta variables def meta(var) raise NoMethodError unless is_full_route? @cur_route - if @meta - @meta[var.to_s] - else - raise "No request has been made yet, so meta data is not available." - end + raise "No request has been made yet, so meta data is not available." unless @meta + @meta[var.to_s] end # Get data from server def get raise NoMethodError unless is_full_route? @cur_route @@ -88,13 +69,31 @@ else super end end - private +private def just_made_request @retrieved_url == @cur_url + end + + def get_next_routes + @next_routes ||= @@routes. + select { |s| s.start_with?(@cur_route) }. + map { |s| s[@cur_route.length..-1] }. + join.split('/').uniq.delete_if(&:empty?) + end + + def get_next_routes_without_params + @next_routes_without_params ||= get_next_routes. + reject { |r| r =~ /^\{.*\}$/ }.map(&:to_sym) + end + + def get_next_routes_with_params + @next_routes_with_params ||= get_next_routes. + select { |r| r =~ /^\{.*\}$/ }. + map { |r| r.delete('{}') }.map(&:to_sym) end def is_in_routes?(substring) @@routes.any? { |s| s.start_with?(substring) } end