Skip to content

Instantly share code, notes, and snippets.

@jackphelps
Created July 15, 2016 21:05
Show Gist options
  • Save jackphelps/b94201f35c0ee32424c6abb1bf991fa7 to your computer and use it in GitHub Desktop.
Save jackphelps/b94201f35c0ee32424c6abb1bf991fa7 to your computer and use it in GitHub Desktop.
Usage:
class MyModel
include ListAttributeHelper
KINDS = %w( stripe paypal )
scopes_and_identities :kind, KINDS
end
MyModel.paypal.size
=> 999
MyModel.stripe.last.stripe?
=> true
MyModel.stripe.last.paypal?
=> false
module ListAttributeHelper
module ClassMethods
def scopes_and_identities(attr_name, arr)
class_eval do
arr.each do |val|
scope val.to_sym, -> { where("#{attr_name} = ?", val) }
define_method("#{val}?".to_sym) { read_attribute(attr_name.to_sym) == val }
end
end
end
end
def self.included(base)
base.extend(ClassMethods)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment