Class: MobicomCandy::Entity

Inherits:
Object
  • Object
show all
Defined in:
lib/mobicom_candy/entity.rb

Constant Summary collapse

PATTERN =
/[\-_]|(?<=\w)(?=[A-Z])/
UNDERSCORE =
'_'.freeze

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(**kwargs) ⇒ Entity

Returns a new instance of Entity.



3
4
5
# File 'lib/mobicom_candy/entity.rb', line 3

def initialize(**kwargs)
  @attributes = kwargs
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args) ⇒ Object



17
18
19
20
21
# File 'lib/mobicom_candy/entity.rb', line 17

def method_missing(name, *args)
  return super unless @attributes.key?(name)

  @attributes[name]
end

Class Method Details

.attribute_name(key) ⇒ Object



45
46
47
48
49
# File 'lib/mobicom_candy/entity.rb', line 45

def self.attribute_name(key)
  return key if key.is_a?(Symbol)

  key.split(PATTERN).join(UNDERSCORE).downcase.to_sym
end

.attribute_namesObject



39
40
41
42
43
# File 'lib/mobicom_candy/entity.rb', line 39

def self.attribute_names
  @attribute_names ||= Hash.new do |hash, key|
    hash[key] = attribute_name(key)
  end
end

Instance Method Details

#==(other) ⇒ Object



23
24
25
# File 'lib/mobicom_candy/entity.rb', line 23

def ==(other)
  other.class == self.class && other.attributes == @attributes
end

#[]=(key, value) ⇒ Object



7
8
9
10
11
# File 'lib/mobicom_candy/entity.rb', line 7

def []=(key, value)
  name = self.class.attribute_names[key]

  @attributes[name] = value
end

#respond_to_missing?(name, include_private = false) ⇒ Boolean

Returns:

  • (Boolean)


13
14
15
# File 'lib/mobicom_candy/entity.rb', line 13

def respond_to_missing?(name, include_private = false)
  @attributes.key?(name) || super
end

#to_hObject



27
28
29
# File 'lib/mobicom_candy/entity.rb', line 27

def to_h
  @attributes
end

#to_json(*a) ⇒ Object



31
32
33
# File 'lib/mobicom_candy/entity.rb', line 31

def to_json(*a)
  @attributes.to_json(*a)
end