Class: ClassKit::Helper

Inherits:
Object
  • Object
show all
Defined in:
lib/class_kit/helper.rb

Instance Method Summary collapse

Constructor Details

#initializeHelper

Returns a new instance of Helper.



4
5
6
7
8
9
# File 'lib/class_kit/helper.rb', line 4

def initialize
  @hash_helper = HashKit::Helper.new
  @json_helper = JsonKit::Helper.new
  @attribute_helper = ClassKit::AttributeHelper.new
  @value_helper = ClassKit::ValueHelper.new
end

Instance Method Details

#from_hash(hash:, klass:) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/class_kit/helper.rb', line 26

def from_hash(hash:, klass:)
  validate_class_kit(klass)

  hash = @hash_helper.symbolize(hash)
  entity = klass.new
  attributes = @attribute_helper.get_attributes(klass)
  attributes.each do |attribute|
    key = attribute[:name]
    type = attribute[:type]

    #if the hash value is nil skip it
    next if hash[key].nil?

    value = if is_class_kit?(type)
              from_hash(hash: hash[key], klass: type)
            elsif type == Array
              hash[key].map do |array_element|
                if attribute[:collection_type].nil?
                  array_element
                else
                  if is_class_kit?(attribute[:collection_type])
                    from_hash(hash: array_element, klass: attribute[:collection_type])
                  else
                    @value_helper.parse(type: attribute[:collection_type], value: array_element)
                  end
                end
              end
            else
              hash[key]
            end

    entity.public_send(:"#{key}=", value)
  end

  entity
end

#from_json(json:, klass:) ⇒ Object



67
68
69
# File 'lib/class_kit/helper.rb', line 67

def from_json(json:, klass:)
  from_hash(hash: JSON.load(json), klass: klass)
end

#is_class_kit?(klass) ⇒ Boolean

Returns:

  • (Boolean)


11
12
13
# File 'lib/class_kit/helper.rb', line 11

def is_class_kit?(klass)
  klass.is_a?(ClassKit)
end

#to_hash(object) ⇒ Object



20
21
22
23
24
# File 'lib/class_kit/helper.rb', line 20

def to_hash(object)
  validate_class_kit(object.class)

  @hash_helper.to_hash(object)
end

#to_json(object) ⇒ Object



63
64
65
# File 'lib/class_kit/helper.rb', line 63

def to_json(object)
  @json_helper.to_json(object)
end

#validate_class_kit(klass) ⇒ Object



15
16
17
18
# File 'lib/class_kit/helper.rb', line 15

def validate_class_kit(klass)
  is_class_kit?(klass) || raise(ClassKit::Exceptions::InvalidClassError,
                                "Class: #{klass} does not implement ClassKit.")
end