aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord/lib/active_record/attribute_decorators.rb
diff options
context:
space:
mode:
authorRafael Mendonça França <rafaelmfranca@gmail.com>2014-06-07 15:09:23 -0300
committerRafael Mendonça França <rafaelmfranca@gmail.com>2014-06-07 15:09:23 -0300
commit4cf63ce3731a43bd98f7b92b43dcf1be99c0b183 (patch)
treec9f1c7f5243629daa263c9f863d596d07f788b17 /activerecord/lib/active_record/attribute_decorators.rb
parentdc73e39b4d40f0965b000f84568f77f126ec8290 (diff)
parent2dca1ba039eb0d1adad089134749a5093b481666 (diff)
downloadrails-4cf63ce3731a43bd98f7b92b43dcf1be99c0b183.tar.gz
rails-4cf63ce3731a43bd98f7b92b43dcf1be99c0b183.tar.bz2
rails-4cf63ce3731a43bd98f7b92b43dcf1be99c0b183.zip
Merge pull request #15546 from sgrif/sg-lazy-decorators
Don't query the database schema when calling `serialize`
Diffstat (limited to 'activerecord/lib/active_record/attribute_decorators.rb')
-rw-r--r--activerecord/lib/active_record/attribute_decorators.rb34
1 files changed, 34 insertions, 0 deletions
diff --git a/activerecord/lib/active_record/attribute_decorators.rb b/activerecord/lib/active_record/attribute_decorators.rb
new file mode 100644
index 0000000000..596161f81d
--- /dev/null
+++ b/activerecord/lib/active_record/attribute_decorators.rb
@@ -0,0 +1,34 @@
+module ActiveRecord
+ module AttributeDecorators # :nodoc:
+ extend ActiveSupport::Concern
+
+ included do
+ class_attribute :attribute_type_decorations, instance_accessor: false # :internal:
+ self.attribute_type_decorations = Hash.new({})
+ end
+
+ module ClassMethods
+ def decorate_attribute_type(column_name, decorator_name, &block)
+ clear_caches_calculated_from_columns
+ column_name = column_name.to_s
+
+ # Create new hashes so we don't modify parent classes
+ decorations_for_column = attribute_type_decorations[column_name]
+ new_decorations = decorations_for_column.merge(decorator_name.to_s => block)
+ self.attribute_type_decorations = attribute_type_decorations.merge(column_name => new_decorations)
+ end
+
+ private
+
+ def add_user_provided_columns(*)
+ super.map do |column|
+ decorations = attribute_type_decorations[column.name].values
+ decorated_type = decorations.inject(column.cast_type) do |type, block|
+ block.call(type)
+ end
+ column.with_type(decorated_type)
+ end
+ end
+ end
+ end
+end