Added visitable magic
Andrew Kane
committed Mar 19, 2014
commit 89c56b780ccd77df256593ad800b209433106ab1
Showing 5
changed files with
27 additions
and 6 deletions
README.md
+6
-6
| @@ | @@ -65,15 +65,16 @@ Visit.group(:referring_domain).count |
| This information is great on its own, but super powerful when combined with other models. | |
| - | You can associate the visit with any model. For instance, when someone places an order: |
| + | Let’s associate orders with visits. |
| ```ruby | |
| - | Order.create( |
| - | visit_id: current_visit.try(:id), |
| - | # ... other attributes ... |
| - | ) |
| + | class Order < ActiveRecord::Base |
| + | visitable |
| + | end |
| ``` | |
| + | When a visitor places an order, the `visit_id` column will be automatically set. Magic! |
| + | |
| To see where most of your orders are coming from, create an association: | |
| ```ruby | |
| @@ | @@ -136,7 +137,6 @@ http://datakick.org/?utm_medium=twitter&utm_campaign=social&utm_source=tweet123 |
| ## TODO | |
| - | - set visit_id automatically on `visitable` models |
| - simple dashboard | |
| - hook to store additional fields | |
| - turn off modules | |
ahoy_matey.gemspec
+1
-0
| @@ | @@ -22,6 +22,7 @@ Gem::Specification.new do |spec| |
| spec.add_dependency "browser", ">= 0.4.0" | |
| spec.add_dependency "geocoder" | |
| spec.add_dependency "referer-parser" | |
| + | spec.add_dependency "request_store" |
| spec.add_development_dependency "bundler", "~> 1.5" | |
| spec.add_development_dependency "rake" | |
ahoy/controller.rb b/lib/ahoy/controller.rb
+3
-0
| @@ | @@ -3,6 +3,9 @@ module Ahoy |
| def self.included(base) | |
| base.helper_method :current_visit | |
| + | base.before_filter do |
| + | RequestStore.store[:ahoy_controller] ||= self |
| + | end |
| end | |
| protected | |
ahoy/model.rb b/lib/ahoy/model.rb
+16
-0
| @@ | @@ -79,5 +79,21 @@ module Ahoy |
| end # end class_eval | |
| end | |
| + | def visitable |
| + | class_eval do |
| + | belongs_to :visit |
| + | |
| + | before_create :set_visit |
| + | |
| + | def set_visit |
| + | if !self.class.column_names.include?("visit_id") |
| + | raise "Add a visit_id column to this table to use visitable" |
| + | else |
| + | self.visit ||= RequestStore.store[:ahoy_controller].try(:send, :current_visit) |
| + | end |
| + | end |
| + | end |
| + | end |
| + | |
| end | |
| end | |
ahoy_matey.rb b/lib/ahoy_matey.rb
+1
-0
| @@ | @@ -2,6 +2,7 @@ require "addressable/uri" |
| require "browser" | |
| require "geocoder" | |
| require "referer-parser" | |
| + | require "request_store" |
| require "ahoy/version" | |
| require "ahoy/controller" | |
| require "ahoy/model" | |