Skip to content

Instantly share code, notes, and snippets.

@bewatts
Created April 30, 2014 01:29
Show Gist options
  • Save bewatts/97173fc32cffa42b1a98 to your computer and use it in GitHub Desktop.
Save bewatts/97173fc32cffa42b1a98 to your computer and use it in GitHub Desktop.
Adding class/instance methods meta-programmatically through ActiveSupport::Concern
#Solution was probably too much overhead for the problem I had at hand - but it was fun.
#Note: This gist assumes Rails.
module Concerns
module LinkedAccountable
extend ActiveSupport::Concern
ACCOUNT_TYPES = ["twitter", "google"]
def self.included(obj)
obj.has_many :linked_accounts, :dependent => :destroy
end
ACCOUNT_TYPES.each do |account_type|
account_bool = ((account_type + "?").to_sym)
find_by_account_type_id = ("find_by_" + account_type + '_id').to_sym
account_id = (account_type + "_id").to_sym
account_type_users = (account_type + "_" + self.class.to_s.downcase.pluralize).to_sym
account = account_type.to_sym
### User.first.google?
define_method account_bool do
self.linked_accounts.send(account).any?
end
### User.first.google
define_method account_type.to_sym do
self.send(account_bool) ? self.linked_accounts.send(account).first : nil
end
### User.first.google_id
define_method account_id do
self.send(account_bool) ? self.send(account).source_id : nil
end
### User.find_by_twitter_id("aggressive_panda")
self.class.send(:define_method, find_by_account_type_id) do |id|
belongs_to_assoc = self.to_s.downcase.to_sym
linked_account = LinkedAccount.includes(belongs_to_assoc).send(account).find_by(source_id: id)
linked_account.nil? ? nil : linked_account.send(belongs_to_assoc)
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment