Class: Hb::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/hb.rb,
lib/hb/key_formatter.rb

Defined Under Namespace

Classes: KeyFormatter

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(object, options = {}) ⇒ Base

Returns a new instance of Base.



13
14
15
16
# File 'lib/hb.rb', line 13

def initialize(object, options = {})
  @object = object
  @instance_options = options
end

Instance Attribute Details

#instance_optionsObject (readonly)

Returns the value of attribute instance_options.



8
9
10
# File 'lib/hb.rb', line 8

def instance_options
  @instance_options
end

#objectObject (readonly)

Returns the value of attribute object.



8
9
10
# File 'lib/hb.rb', line 8

def object
  @object
end

Class Method Details

.attribute(attr, options = {}) ⇒ Object



25
26
27
28
29
# File 'lib/hb.rb', line 25

def attribute(attr, options = {})
  key = options.fetch(:key, attr)
  # https://apidock.com/rails/Class/class_attribute
  self._attributes_data = _attributes_data.merge({ key => attr })
end

.attributes(*args) ⇒ Object



19
20
21
22
23
# File 'lib/hb.rb', line 19

def attributes(*args)
  args.each do |attr|
    attribute(attr)
  end
end

.key_format(*args) ⇒ Object



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

def key_format(*args)
  self.key_formatter = KeyFormatter.new(*args)
end

Instance Method Details

#to_hashObject Also known as: to_h



36
37
38
39
40
41
42
43
44
45
46
# File 'lib/hb.rb', line 36

def to_hash
  hash = self.class._attributes_data.each_with_object({}) do |(key, attr), result|
    if respond_to?(attr)
      result[key] = send(attr)
    else
      result[key] = object.send(attr)
    end
  end

  format(hash)
end