Last active
March 21, 2017 23:04
-
-
Save blaze182/4ef54dfdc00026df0bdf3a0b583d600c to your computer and use it in GitHub Desktop.
Rails enum getter for transient attributes
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
# Rails enum does not decorate transient attribute getters | |
# This concern aims to set getters if enum for | |
# transient attribute has been defined. | |
# | |
# Also enables question? methods. | |
# | |
# Example usage: | |
# class Model < ActiveRecord::Base | |
# include TransientEnumerable | |
# | |
# attr_writer :transient_state # <- please use writer only | |
# | |
# enum transient_state: { | |
# inactive: 0, | |
# active: 1 | |
# } | |
# | |
# transient_enum_decorate :transient_state | |
# | |
# ... | |
# end | |
# | |
module TransientEnumerable | |
extend ActiveSupport::Concern | |
class_methods do | |
def transient_enum_decorate(*attributes) | |
attributes.each do |attr| | |
mapping = self.send(attr.to_s.pluralize) | |
define_method(attr) do | |
value = instance_variable_get("@" + attr.to_s) | |
return unless value | |
if mapping.has_key?(value) | |
value.to_s | |
elsif mapping.has_value?(value.to_i) | |
mapping.key(value.to_i) | |
else | |
raise ArgumentError, "'#{value}' is not a valid #{attr.to_s}" | |
end | |
end | |
# Redefine enum question? helper methods | |
mapping.each do |value, i| | |
define_method("#{value}?") { self.public_send(attr) == value.to_s } | |
end | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment