class Statham::Attribute
Internal: Attributes serialized inside JSON.
Attributes
default[RW]
Internal: Default value for the attribute.
type[RW]
Internal: Type of the attribute.
Public Class Methods
new(options = {})
click to toggle source
Internal: Initialize the attribute.
options - The hash options used for defining new attributes:
type - Type of the attribute. default - Default value for the attribute.
Returns new Statham::Attribute
object.
# File lib/statham/attribute.rb, line 16 def initialize(options = {}) @type = options[:type] @default = options[:default] end
Public Instance Methods
deserialize(value, options = {})
click to toggle source
Internal: Deserializes JSON-compatible value to native one.
value - Value to deserialize.
Returns deserialized value.
# File lib/statham/attribute.rb, line 37 def deserialize(value, options = {}) if options[:fallback_to_default] value || @default else value end end
serialize(value)
click to toggle source
Internal: Serializes value to be JSON-compatible.
value - Value to serialize.
Returns serialized value.
# File lib/statham/attribute.rb, line 26 def serialize(value) serialized = value.nil? ? nil : casted_to_type(value) serialized.nil? && !@default.nil? ? @default : serialized end
Protected Instance Methods
casted_to_type(value)
click to toggle source
Internal: Casts value to type defined for the attribute.
value - Value to cast type.
Returns value with type casted.
# File lib/statham/attribute.rb, line 52 def casted_to_type(value) case @type when :boolean [true, 1, '1', 't', 'T', 'true', 'TRUE', 'on', 'ON'].include?(value) when :integer value.to_i when :array value.to_a when :hash value.to_h when :float value.to_f else value.to_s end end