Created
April 25, 2014 19:35
-
-
Save cheeyeo/11300553 to your computer and use it in GitHub Desktop.
Mixpanel generic module as a mixin in AR using ActiveSupport
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
| # using active_support | |
| require 'active_support/core_ext' | |
| module Mixpanel | |
| extend ActiveSupport::Concern | |
| # class methods | |
| included do | |
| mixpanel | |
| end | |
| # instance methods | |
| def to_mixpanel | |
| res = self.mp_attrs.reduce({}) {|memo, attr| | |
| target = send(attr) | |
| memo[attr] = target.respond_to?(:item_value) ? target.item_value : target | |
| memo | |
| } | |
| end | |
| module ClassMethods | |
| def mixpanel(*names) | |
| cattr_accessor :mp_attrs | |
| self.mp_attrs = names | |
| end | |
| end | |
| end | |
| class Test < Object | |
| include Mixpanel | |
| attr_accessor :name, :desc | |
| mixpanel :name, :desc | |
| end | |
| t = Test.new | |
| t.name = "Foo" | |
| t.desc = "Description" | |
| p t.to_mixpanel |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment