Module: Familia::Features::SafeDump
- Defined in:
- lib/familia/features/safe_dump.rb
Overview
SafeDump is a mixin that allows models to define a list of fields that are safe to dump. This is useful for serializing objects to JSON or other formats where you want to ensure that only certain fields are exposed.
To use SafeDump, include it in your model and use the DSL methods to define safe dump fields. The fields can be either symbols or hashes. If a field is a symbol, the method with the same name will be called on the object to retrieve the value. If the field is a hash, the key is the field name and the value is a lambda that will be called with the object as an argument. The hash syntax allows you to:
- define a field name that is different from the method name
- define a field that requires some computation on-the-fly
- define a field that is not a method on the object
Example:
feature :safe_dump
safe_dump_field :objid safe_dump_field :updated safe_dump_field :created safe_dump_field :active, ->(obj) { obj.active? }
Alternatively, you can define multiple fields at once:
safe_dump_fields :objid, :updated, :created, { active: ->(obj) { obj.active? } }
Internally, all fields are normalized to the hash syntax and stored in
@safe_dump_field_map. SafeDump.safe_dump_fields returns only the list
of symbols in the order they were defined.
Defined Under Namespace
Modules: ModelClassMethods
Instance Method Summary collapse
-
#safe_dump ⇒ Object
Returns a hash of safe fields and their values.
Instance Method Details
#safe_dump ⇒ Object
Returns a hash of safe fields and their values. This method calls the callables defined in the safe_dump_field_map with the instance object as an argument.
The return values are not cached, so if you call this method multiple times, the callables will be called each time.
Example:
class Customer < Familia::HashKey include SafeDump @safe_dump_fields = [ :name, { :active => ->(cust) { cust.active? } } ]
def active?
true # or false
end
cust = Customer.new :name => 'Lucy'
cust.safe_dump
#=> { :name => 'Lucy', :active => true }
137 138 139 140 141 142 143 144 145 146 147 148 149 |
# File 'lib/familia/features/safe_dump.rb', line 137 def safe_dump self.class.safe_dump_field_map.transform_values do |callable| transformed_value = callable.call(self) # If the value is a relative ancestor of SafeDump we can # call safe_dump on it, otherwise we'll just return the value as-is. if transformed_value.is_a?(SafeDump) transformed_value.safe_dump else transformed_value end end end |