/
location.rb
65 lines (52 loc) · 1.31 KB
/
location.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
module Picky
module Calculations # :nodoc:all
# A location calculation recalculates a 1-d location
# to the Picky internal 1-d "grid".
#
# For example, if you have a location x == 12.3456,
# it will be recalculated into 3, if the minimum is 9
# and the gridlength is 1.
#
class Location
attr_reader :anchor,
:precision,
:grid
def initialize user_grid, anchor = 0.0, precision = nil
@user_grid = user_grid
@precision = precision || 1
@grid = @user_grid / (@precision + 0.5)
self.anchor = anchor
end
def anchor= value
# Add a margin of 1 user grid.
#
value -= @user_grid
# Add plus 1 grid so that the index key never falls on 0.
# Why? to_i maps by default to 0.
#
value -= @grid
@anchor = value
end
#
#
def add_margin length
@anchor -= length
end
#
#
def calculated_range location
range calculate(location)
end
#
#
def range around_location
(around_location - @precision)..(around_location + @precision)
end
#
#
def calculate location
((location - @anchor) / @grid).floor
end
end
end
end