Skip to content

Instantly share code, notes, and snippets.

@joekhoobyar
Last active December 17, 2015 21:49
Show Gist options
  • Save joekhoobyar/5677399 to your computer and use it in GitHub Desktop.
Save joekhoobyar/5677399 to your computer and use it in GitHub Desktop.
A simple ActiveRecord extension for declaring raw attributes (not backed by a database column) that should work with composed_of, associations, etc.
class ActiveRecord::Base
# Defines a shorthand for declaring raw attributes that are not backed by a database column.
#
# Equivalent to manually defining getter/setter/query methods that call read/write/query_attribute,
# but also supports attribute names with characters that are not allowed in normal method names.
# Unlike +attr_accessor+, these attributes should work with +composed_of+, associations, etc.
#
def self.attribute(*names)
names.each do |name|
# Define getter, setter and query, supporting characters that are not allowed in normal method names.
# We prefer +class_eval+ over +define_method+, since the latter creates a closure.
class_eval <<-STR, __FILE__, __LINE__ + 1
def __temp__()
read_attribute(#{name.inspect})
end
alias_method '#{name}', :__temp__
undef_method :__temp__
STR
class_eval <<-STR, __FILE__, __LINE__ + 1
def __temp__=(value)
write_attribute(#{name.inspect}, value)
end
alias_method '#{name}=', :__temp__=
undef_method :__temp__=
STR
class_eval <<-STR, __FILE__, __LINE__ + 1
def __temp__?(value)
query_attribute(#{name.inspect})
end
alias_method '#{name}?', :__temp__?
undef_method :__temp__?
STR
end
end
end if defined? ActiveRecord::Base
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment