Skip to content

Instantly share code, notes, and snippets.

@cheeyeo
Last active August 29, 2015 14:00
Show Gist options
  • Save cheeyeo/11300942 to your computer and use it in GitHub Desktop.
Save cheeyeo/11300942 to your computer and use it in GitHub Desktop.
Mixpanel module as mixin for Activerecord classes
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
@cheeyeo
Copy link
Author

cheeyeo commented Apr 26, 2014

Change to class_attribute as subclasses will be able to define their own mp_attrs without affecting base class

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment