Class: ClassKit::Helper

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

Instance Method Summary collapse

Constructor Details

#initialize ⇒ Helper

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



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
62
63
64
65
66
67
68
69
# File 'lib/class_kit/helper.rb', line 35

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 |a|
    key = a[:name]
    type = a[:type]

    #if the hash value is nil skip it
    if hash[key] == nil
      next
    end

    if is_class_kit?(type)
      value = from_hash(hash: hash[key], klass: type)
    elsif type == Array
      value = hash[key].map do |i|
        if a[:collection_type] != nil
          if is_class_kit?(a[:collection_type])
            from_hash(hash: i, klass: a[:collection_type])
          else
            @value_helper.parse(type: a[:collection_type], value: i)
          end
        else
          i
        end
      end
    else
      value = hash[key]
    end
    eval("entity.#{key}=value")
  end
  return entity
end

#from_json(json:, klass:) ⇒ Object



75
76
77
78
# File 'lib/class_kit/helper.rb', line 75

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

#is_class_kit?(klass) ⇒ Boolean

Returns:

  • (Boolean)


11
12
13
14
15
16
17
18
19
20
21
# File 'lib/class_kit/helper.rb', line 11

def is_class_kit?(klass)
  begin
    if !klass.class_variable_defined?(:@@is_class_kit_class)
      return false
    end
  rescue
    return false
  end

  return true
end

#to_hash(object) ⇒ Object



30
31
32
33
# File 'lib/class_kit/helper.rb', line 30

def to_hash(object)
  validate_class_kit(object.class)
  return @hash_helper.to_hash(object)
end

#to_json(object) ⇒ Object



71
72
73
# File 'lib/class_kit/helper.rb', line 71

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

#validate_class_kit(klass) ⇒ Object



23
24
25
26
27
28
# File 'lib/class_kit/helper.rb', line 23

def validate_class_kit(klass)
  if !is_class_kit?(klass)
    raise ClassKit::Exceptions::InvalidClassError.new("Class: #{klass} does not implement ClassKit.")
  end
  return true
end