Module: Ruact::Serializable

Defined in:
lib/ruact/serializable.rb

Overview

Include this module in any Ruby object you want to pass as a prop to a client component. Declare which attributes are safe to serialize with ruact_props; only those attributes will be included in the wire payload.

Works on POROs and on ActiveRecord models alike. For a PORO the loud check fires at class-load; for an ActiveRecord model (whose attribute readers are defined lazily) the same loud check is deferred to the first ruact_serialize — see ClassMethods#ruact_props.

Examples:

PORO

class Post
  include Ruact::Serializable
  attr_reader :id, :title, :secret
  ruact_props :id, :title   # :secret is never sent to the client
end

ActiveRecord model

class Post < ApplicationRecord
  include Ruact::Serializable
  ruact_props :id, :title   # other columns never cross to the client
end

Defined Under Namespace

Modules: ClassMethods

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



26
27
28
29
30
# File 'lib/ruact/serializable.rb', line 26

def self.included(base)
  base.extend(ClassMethods)
  base.instance_variable_set(:@ruact_props, [])
  base.instance_variable_set(:@ruact_deferred_props, [])
end

Instance Method Details

#ruact_serializeHash{String => Object}

Serialize only the attributes declared with ruact_props.

Returns:

  • (Hash{String => Object})


145
146
147
148
# File 'lib/ruact/serializable.rb', line 145

def ruact_serialize
  self.class.ruact_validate_deferred_props!(self)
  self.class.ruact_props_list.to_h { |attr| [attr.to_s, public_send(attr)] }
end