Nenhuma Descrição http://j1x-huginn.herokuapp.com

location.rb 1.4KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. Location = Struct.new(:lat, :lng, :radius, :speed, :course)
  2. class Location
  3. protected :[]=
  4. def initialize(data = {})
  5. super()
  6. case data
  7. when Array
  8. raise ArgumentError, 'unsupported location data' unless data.size == 2
  9. self.lat, self.lng = data
  10. when Hash, Location
  11. data.each { |key, value|
  12. begin
  13. __send__("#{key}=", value)
  14. rescue NameError
  15. end
  16. }
  17. else
  18. raise ArgumentError, 'unsupported location data'
  19. end
  20. yield self if block_given?
  21. end
  22. def lat=(value)
  23. self[:lat] = floatify(value) { |f|
  24. if f.abs <= 90
  25. f
  26. else
  27. raise ArgumentError, 'out of bounds'
  28. end
  29. }
  30. end
  31. def lng=(value)
  32. self[:lng] = floatify(value) { |f|
  33. if f.abs <= 180
  34. f
  35. else
  36. raise ArgumentError, 'out of bounds'
  37. end
  38. }
  39. end
  40. def radius=(value)
  41. self[:radius] = floatify(value) { |f| f if f >= 0 }
  42. end
  43. def speed=(value)
  44. self[:speed] = floatify(value) { |f| f if f >= 0 }
  45. end
  46. def course=(value)
  47. self[:course] = floatify(value) { |f| f if (0..360).cover?(f) }
  48. end
  49. def present?
  50. lat && lng
  51. end
  52. def empty?
  53. !present?
  54. end
  55. private
  56. def floatify(value)
  57. case value
  58. when nil, ''
  59. return nil
  60. else
  61. float = Float(value)
  62. if block_given?
  63. yield(float)
  64. else
  65. float
  66. end
  67. end
  68. end
  69. end