Last active
August 29, 2015 14:00
-
-
Save cheeyeo/11300942 to your computer and use it in GitHub Desktop.
Mixpanel module as mixin for Activerecord classes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'active_support/core_ext' | |
module Mixpanel | |
module ClassMethods | |
def mixpanel(*names) | |
# Defines both class and instance accessors for class attributes. | |
class_attribute :mp_attrs | |
self.mp_attrs = names | |
end | |
end | |
# instance methods | |
def to_mixpanel | |
self.mp_attrs.reduce({}) {|memo, attr| | |
target = send(attr) | |
memo[attr] = target.respond_to?(:item_value) ? target.item_value : target | |
memo | |
} | |
end | |
def self.included(base) | |
base.extend ClassMethods | |
end | |
end | |
class Foo < Object | |
include Mixpanel | |
attr_accessor :name | |
mixpanel :name | |
def to_s | |
"Foo" | |
end | |
end | |
class Bar < Object | |
include Mixpanel | |
attr_accessor :desc, :name | |
mixpanel :name, :desc | |
def to_s | |
"Bar" | |
end | |
end | |
class Foo2 < Foo | |
attr_accessor :name2 | |
mixpanel :name2 | |
end | |
t = Foo.new | |
t.name = "Foo" | |
p t.mp_attrs | |
p t | |
p t.to_mixpanel | |
t = Bar.new | |
t.name = "Bar" | |
t.desc = "Bar" | |
p t.mp_attrs | |
p t | |
p t.to_mixpanel | |
t3 = Foo2.new | |
t3.name2 = "Foo 2" | |
p t3.mp_attrs |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Change to class_attribute as subclasses will be able to define their own mp_attrs without affecting base class