Last active
May 10, 2017 20:35
-
-
Save yuroyoro/4378351 to your computer and use it in GitHub Desktop.
AttrInquirable wraps value of attribute in ActiveSupport::StringInquirer.
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
# 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