Skip to content

Instantly share code, notes, and snippets.

@yuroyoro
Last active May 10, 2017 20:35
Show Gist options
  • Save yuroyoro/4378351 to your computer and use it in GitHub Desktop.
Save yuroyoro/4378351 to your computer and use it in GitHub Desktop.
AttrInquirable wraps value of attribute in ActiveSupport::StringInquirer.
# AttrInquirable
# wraps value of attribute in ActiveSupport::StringInquirer.
#
# Usage:
#
# class Person < ActiveRecord::Base
# attr_inquireable :status
# end
#
# person = Person.new(:status => :pending)
# person.status.pending? # true
# person.status == "pending" # true
#
module AttrInquirable
module ClassMethods
def attr_inquireable(*columns)
columns.to_a.each do |column|
has_accessor_method = self.instance_methods.include?(column.to_s)
method_name = has_accessor_method ? "#{column.to_s}_with_inquiry" : column.to_s
define_method(method_name){
(has_accessor_method ? send("#{column}_without_inquiry") : read_attribute(column)).try{|v|
ActiveSupport::StringInquirer.new(v.to_s).tap{|inc|
inc.class_eval do
def ==(that)
case that
when Symbol then self.to_sym == that
else super that
end
end
end
}
}
}
alias_method_chain column, :inquiry if has_accessor_method
end
end
end
def self.included(base)
base.extend ClassMethods
end
end
ActiveRecord::Base.extend AttrInquirable::ClassMethods
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment