method
serializable_hash
v7.1.3.4 -
Show latest stable
-
0 notes -
Class: ActiveModel::Serialization
- 1.0.0
- 1.1.6
- 1.2.6
- 2.0.3
- 2.1.0
- 2.2.1
- 2.3.8
- 3.0.0 (0)
- 3.0.9 (0)
- 3.1.0 (0)
- 3.2.1 (0)
- 3.2.8 (0)
- 3.2.13 (0)
- 4.0.2 (33)
- 4.1.8 (0)
- 4.2.1 (0)
- 4.2.7 (0)
- 4.2.9 (0)
- 5.0.0.1 (38)
- 5.1.7 (0)
- 5.2.3 (0)
- 6.0.0 (0)
- 6.1.3.1 (0)
- 6.1.7.7 (0)
- 7.0.0 (0)
- 7.1.3.2 (0)
- 7.1.3.4 (0)
- What's this?
serializable_hash(options = nil)
public
Returns a serialized hash of your object.
class Person include ActiveModel::Serialization attr_accessor :name, :age def attributes {'name' => nil, 'age' => nil} end def capitalized_name name.capitalize end end person = Person.new person.name = 'bob' person.age = 22 person.serializable_hash # => {"name"=>"bob", "age"=>22} person.serializable_hash(only: :name) # => {"name"=>"bob"} person.serializable_hash(except: :name) # => {"age"=>22} person.serializable_hash(methods: :capitalized_name) # => {"name"=>"bob", "age"=>22, "capitalized_name"=>"Bob"}
Example with :include option
class User include ActiveModel::Serializers::JSON attr_accessor :name, :notes # Emulate has_many :notes def attributes {'name' => nil} end end class Note include ActiveModel::Serializers::JSON attr_accessor :title, :text def attributes {'title' => nil, 'text' => nil} end end note = Note.new note.title = 'Battle of Austerlitz' note.text = 'Some text here' user = User.new user.name = 'Napoleon' user.notes = [note] user.serializable_hash # => {"name" => "Napoleon"} user.serializable_hash(include: { notes: { only: 'title' }}) # => {"name" => "Napoleon", "notes" => [{"title"=>"Battle of Austerlitz"}]}