Skip to content

Commit

Permalink
Added instance method - #460
Browse files Browse the repository at this point in the history
  • Loading branch information
ankane committed Dec 4, 2020
1 parent 16ee9ff commit f4aef5e
Show file tree
Hide file tree
Showing 6 changed files with 33 additions and 5 deletions.
3 changes: 2 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
## 3.0.6 (unreleased)
## 3.1.0 (unreleased)

- Added `instance` method
- Added optional `request` to `user_method` option

## 3.0.5 (2020-09-09)
Expand Down
8 changes: 8 additions & 0 deletions lib/ahoy.rb
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,14 @@ def self.mask_ip(ip)
addr.mask(48).to_s
end
end

def self.instance
Thread.current[:ahoy]
end

def self.instance=(value)
Thread.current[:ahoy] = value
end
end

ActiveSupport.on_load(:action_controller) do
Expand Down
6 changes: 3 additions & 3 deletions lib/ahoy/controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -39,12 +39,12 @@ def track_ahoy_visit
end

def set_ahoy_request_store
previous_value = Thread.current[:ahoy]
previous_value = Ahoy.instance
begin
Thread.current[:ahoy] = ahoy
Ahoy.instance = ahoy
yield
ensure
Thread.current[:ahoy] = previous_value
Ahoy.instance = previous_value
end
end
end
Expand Down
2 changes: 1 addition & 1 deletion lib/ahoy/model.rb
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ def visitable(name = :visit, **options)
end
class_eval %{
def set_ahoy_visit
self.#{name} ||= Thread.current[:ahoy].try(:visit_or_create)
self.#{name} ||= Ahoy.instance.try(:visit_or_create)
end
}
end
Expand Down
13 changes: 13 additions & 0 deletions test/controller_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,19 @@ def test_visitable
assert_equal visit, Product.last.ahoy_visit
end

def test_instance
post products_url
assert_response :success

assert_equal 1, Ahoy::Visit.count
assert_equal 1, Ahoy::Event.count

event = Ahoy::Event.last
assert_equal "Created product", event.name
product = Product.last
assert_equal({"product_id" => product.id}, event.properties)
end

def test_authenticate
get products_url
visit = Ahoy::Visit.last
Expand Down
6 changes: 6 additions & 0 deletions test/internal/app/models/product.rb
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
class Product < ApplicationRecord
visitable :ahoy_visit

after_create :track_create

def track_create
Ahoy.instance.track("Created product", product_id: id)
end
end

0 comments on commit f4aef5e

Please sign in to comment.