File tree Expand file tree Collapse file tree 2 files changed +26
-4
lines changed Expand file tree Collapse file tree 2 files changed +26
-4
lines changed Original file line number Diff line number Diff line change @@ -112,19 +112,26 @@ def self.attributes(*attrs)
112
112
# attributes :id, :recent_edits
113
113
# attribute :name, key: :title
114
114
#
115
+ # attribute :full_name do
116
+ # "#{object.first_name} #{object.last_name}"
117
+ # end
118
+ #
115
119
# def recent_edits
116
120
# object.edits.last(5)
117
121
# end
118
- def self . attribute ( attr , options = { } )
122
+ def self . attribute ( attr , options = { } , & block )
119
123
key = options . fetch ( :key , attr )
120
124
_attributes_keys [ attr ] = { key : key } if key != attr
121
- _attributes << key unless _attributes . include? ( key )
122
125
123
- serialized_attributes [ key ] = -> ( object ) { object . read_attribute_for_serialization ( attr ) }
126
+ if block_given?
127
+ serialized_attributes [ key ] = -> ( instance ) { instance . instance_eval ( &block ) }
128
+ else
129
+ serialized_attributes [ key ] = -> ( instance ) { instance . object . read_attribute_for_serialization ( attr ) }
130
+ end
124
131
125
132
ActiveModelSerializers . silence_warnings do
126
133
define_method key do
127
- serialized_attributes [ key ] . call ( object )
134
+ serialized_attributes [ key ] . call ( self )
128
135
end unless method_defined? ( key ) || _fragmented . respond_to? ( attr )
129
136
end
130
137
end
Original file line number Diff line number Diff line change @@ -71,6 +71,21 @@ def id
71
71
72
72
assert_equal ( 'custom' , hash [ :blog ] [ :id ] )
73
73
end
74
+
75
+ PostWithVirtualAttribute = Class . new ( ::Model )
76
+ class PostWithVirtualAttributeSerializer < ActiveModel ::Serializer
77
+ attribute :name do
78
+ "#{ object . first_name } #{ object . last_name } "
79
+ end
80
+ end
81
+
82
+ def test_virtual_attribute_block
83
+ post = PostWithVirtualAttribute . new ( first_name : 'Lucas' , last_name : 'Hosseini' )
84
+ hash = serializable ( post ) . serializable_hash
85
+ expected = { name : 'Lucas Hosseini' }
86
+
87
+ assert_equal ( expected , hash )
88
+ end
74
89
end
75
90
end
76
91
end
You can’t perform that action at this time.
0 commit comments