Module: SmoothOperator::Serialization

Included in:
OpenStruct
Defined in:
lib/smooth_operator/serialization.rb

Instance Method Summary collapse

Instance Method Details

#read_attribute_for_serialization(attribute) ⇒ Object



17
18
19
# File 'lib/smooth_operator/serialization.rb', line 17

def read_attribute_for_serialization(attribute)
  send(attribute)
end

#serializable_hash(options = nil) ⇒ Object

Code inspired in ActiveSupport#serializable_hash



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/smooth_operator/serialization.rb', line 21

def serializable_hash(options = nil) # Code inspired in ActiveSupport#serializable_hash
  options ||= {}

  attribute_names = internal_data.keys.sort

  if only = options[:only]
    attribute_names &= [*only].map(&:to_s)
  elsif except = options[:except]
    attribute_names -= [*except].map(&:to_s)
  end

  method_names = [*options[:methods]].select { |n| respond_to?(n) }

  hash = {}
  
  attribute_names.each { |attribute_name| hash[attribute_name] = read_attribute_for_hashing(attribute_name, options) }
  method_names.each { |method_name| hash[method_name.to_s] = send(method_name) }

  hash
end

#to_hash(options = nil) ⇒ Object Also known as: attributes



5
6
7
# File 'lib/smooth_operator/serialization.rb', line 5

def to_hash(options = nil)
  Helpers.symbolyze_keys serializable_hash(options)
end

#to_json(options = nil) ⇒ Object



11
12
13
14
15
# File 'lib/smooth_operator/serialization.rb', line 11

def to_json(options = nil)
  require 'json' unless defined? JSON
  
  JSON(serializable_hash(options))
end