Sha256: 9a69e600aa137de98d342b118573a1c678013ea8dd49de9ff1fb7f52a67a7c27
Contents?: true
Size: 1.67 KB
Versions: 5
Compression:
Stored size: 1.67 KB
Contents
require "active_support" module Hexx # Contains +attr_coerced+ public class method. # # Include the module into the Rails model: # # require "hexx" # require_relative "attributes/string" # # class User < ActiveRecord::Base # include Hexx::Models # # # coerces attributes # attr_coerced :name, login, type: Attributes::String # end # module Models extend ActiveSupport::Concern # Model class helpers for attributes coercion. module ClassMethods def attr_coerced(*names, type:) names.each { |name| _attr_coerced(name, type) } end private def _attr_coerced(name, type) if ancestors.map(&:name).include? "ActiveRecord::Base" coerce_activerecord_reader name, type coerce_activerecord_writer name, type else coerce_simple_reader name, type coerce_simple_writer name, type end end def coerce_simple_reader(name, type) class_eval( "def #{ name }; #{ type.name }.new(@#{ name }); end" ) end def coerce_simple_writer(name, type) class_eval( "def #{ name }=(value); @#{ name } = #{ type.name }.new(value); end" ) end def coerce_activerecord_reader(name, type) class_eval( "def #{ name }; #{ type.name }.new read_attribute(:#{ name }); end" ) end def coerce_activerecord_writer(name, type) class_eval( "def #{ name }=(value); write_attribute :#{ name }, #{ type.name }.new(value); end" ) end end end end
Version data entries
5 entries across 5 versions & 1 rubygems
Version | Path |
---|---|
hexx-1.1.1 | lib/hexx/models.rb |
hexx-1.1.0 | lib/hexx/models.rb |
hexx-1.0.2 | lib/hexx/models.rb |
hexx-1.0.1 | lib/hexx/models.rb |
hexx-1.0.0 | lib/hexx/models.rb |