Class: SimpleSchema::Converter

Inherits:
Object
  • Object
show all
Defined in:
lib/simple_schema/converter.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(schema, options = {}) ⇒ Converter

Returns a new instance of Converter.



5
6
7
8
9
10
11
# File 'lib/simple_schema/converter.rb', line 5

def initialize(schema, options = {})
  options[:translates] ||= [ConverterItems,ConverterProperties]
  options[:filters] ||= [FilterItems,FilterProperties]
  @schema = schema
  @schema = @schema.schema if @schema.respond_to?(:schema)
  @options = options
end

Instance Attribute Details

#optionsObject (readonly)

Returns the value of attribute options.



3
4
5
# File 'lib/simple_schema/converter.rb', line 3

def options
  @options
end

#schemaObject (readonly)

Returns the value of attribute schema.



3
4
5
# File 'lib/simple_schema/converter.rb', line 3

def schema
  @schema
end

Instance Method Details

#filter(data, filter) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/simple_schema/converter.rb', line 40

def filter(data, filter)
  translated_data  = {}
  @schema.each do |key, properties|
    #todo: pode ser escolhida a estrategia apenas 1 vez
    if data.respond_to?(:fetch)
      value = data.fetch(key, nil)
    elsif data.respond_to?(:read_attribute)
      value = data.read_attribute(key)
    elsif data.respond_to?(key)
      value = data.send(key)
    else
      raise InvalidDataType.new(data.class)
    end

    @options[:filters].each do |normalizer|
      value = normalizer.build(value, properties, @options , filter)
    end

    translated_data[key] = value if properties[:roles].include?(filter) #&& !value.nil?
  end

  translated_data

end

#translate(data) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/simple_schema/converter.rb', line 13

def translate(data)
  translated_data  = {}

  @schema.each do |key, properties|

    translated_key = SimpleSchema.translate(key, properties[:key_name])
    #todo: pode ser escolhida a estrategia apenas 1 vez
    if data.respond_to?(:fetch)
      value = data.fetch(key, nil)
    elsif data.respond_to?(:read_attribute)
      value = data.read_attribute(key)
    elsif data.respond_to?(key)
      value = data.send(key)
    else
      raise InvalidDataType.new(data.class)
    end

    @options[:translates].each do |normalizer|
      value = normalizer.build(value, properties, @options)
    end

    translated_data[translated_key] = value
  end

  translated_data
end